首頁  >  問答  >  主體

Laravel 9 Eloquent 模型 - 模型中保留的列名稱

<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 "); LINE 1: update "mytable" set "a_property_of_the_attributes_jsonb_field" = $1 where "mypk" = ...</pre> <p>我無法重新命名該列,因為其他非 PHP 專案正在使用該資料庫。 </p> <p>如何將模型中的「屬性」欄位作為 ArrayObject 存取? </p>
P粉309989673P粉309989673384 天前499

全部回覆(1)我來回復

  • P粉034571623

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

    簡單的解決方法是使用 ArrayObject 存取器方法:

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

    注意:仍然需要定義「attributes」轉換才能以陣列形式存取底層 jsonb 欄位:

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

    回覆
    0
  • 取消回覆