Laravel 9 Eloquent model - retained column names in model
P粉309989673
P粉309989673 2023-09-03 14:36:02
0
1
574
<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粉309989673
P粉309989673

reply all(1)
P粉034571623

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
];
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template