Laravel 9 Eloquent 模型 - 模型中保留的列名称
P粉309989673
P粉309989673 2023-09-03 14:36:02
0
1
493
<p>我有一个 postgres 数据库,其中有一个表,其中有一列名为“attributes”。</p> <p>属性列是 jsonb 类型,因此我使用 Eloquent 转换:</p> <pre class="lang-php prettyprint-override"><code>protected $casts = [ 'attributes' => AsArrayObject::class, ]; </code></pre> <p>这似乎会导致问题,因为“属性”已经是 Eloquent 模型属性,并且似乎没有任何别名列名称的规定。</p> <p>所以这一行:</p> <pre class="lang-php prettyprint-override"><code>$this->attributes['a_property_of_the_attributes_jsonb_field'] = 'hello word!'; </code></pre> <p>似乎正在访问内部 Eloquent 模型属性 - 而不是我的数据库表中的“attributes”字段,从而导致以下错误:</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>我无法重命名该列,因为其他非 PHP 项目正在使用该数据库。</p> <p>如何将模型中的“属性”字段作为 ArrayObject 进行访问?</p>
P粉309989673
P粉309989673

全部回复(1)
P粉034571623

简单的解决方法是使用 ArrayObject 访问器方法:

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

注意:仍然需要定义“attributes”转换才能以数组形式访问底层 jsonb 字段:

protected $casts = [
    'attributes' => AsArrayObject::class
];
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!