Home  >  Q&A  >  body text

Laravel 9 Eloquent model - retained column names in model

<p>I have a postgres database with a table that has a column called "attributes". </p> <p>The attribute column is of jsonb type, so I use Eloquent conversion: </p> <pre class="lang-php prettyprint-override"><code>protected $casts = [ 'attributes' => AsArrayObject::class, ]; </code></pre> <p>This seems to cause problems because the "property" is already an Eloquent model property, and there doesn't seem to be any provision for aliasing column names. </p> <p>So this line:</p> <pre class="lang-php prettyprint-override"><code>$this->attributes['a_property_of_the_attributes_jsonb_field'] = 'hello word!'; </code></pre> <p>Appears to be accessing an internal Eloquent model attribute - rather than the 'attributes' field in my database table, resulting in the following error:</p> <pre class="brush:php;toolbar:false;">SQLSTATE[42703]: Undefined column: 7 ERROR: column "a_property_of_the_attributes_jsonb_field" of relation "mytable" does not exist LINE 1: update "mytable" set "a_property_of_the_attributes_jsonb_field" = $1 where "mypk" = ...</pre> <p>I cannot rename the column because other non-PHP projects are using the database. </p> <p>How can I access the Property field in my model as an ArrayObject? </p>
P粉309989673P粉309989673384 days ago497

reply all(1)I'll reply

  • P粉034571623

    P粉0345716232023-09-04 12:12:46

    The simple solution is to use the ArrayObject accessor method:

    $this['attributes'] = ['x' => 'y'];
    $stuff = $this['attributes'];

    NOTE: The "attributes" transformation still needs to be defined to access the underlying jsonb field as an array:

    protected $casts = [
        'attributes' => AsArrayObject::class
    ];

    reply
    0
  • Cancelreply