簡體   English   中英

Laravel 5.4:雄辯的sync()不使用模型的變量或屬性轉換?

[英]Laravel 5.4: Eloquent sync() not using model's mutator or attribute casting?

變量和屬性轉換

我有一個帶有“修改”屬性的模型。 該模型使用set屬性。 這是因為存儲被保存為布爾值,但是該屬性是通過選擇進行管理的(因為可用的FE選項處於三種狀態:[無|修改|訪問],其中“無”不存儲在BE中。

存儲如下(mysql):

+-------------+------------------+------+-----+---------+-------+
| Field       | Type             | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+-------+
| prop_id     | int(10) unsigned | NO   | PRI | NULL    |       |
| modify      | tinyint(1)       | NO   |     | 1       |       |
+-------------+------------------+------+-----+---------+-------+

該模型使用以下mutator方法將“ modify”轉換為true。

public function setModifyAttribute($value)
{
    $this->attributes['modify'] = ($value === "modify");
}

傳遞給sync()的典型集合如下:

$properties = 
Collection {
  #items: array [
    1 => array [
      "modify" => "modify"
    ]
    7 => array [
      "modify" => "access"
    ]
  ]
}

然后,我為屬性調用sync,如下所示:

$this->properties()->sync($properties);

但是,不會從sync()訪問setModifyAttribute()。

或者,使用值'true'和'false'sync()似乎忽略了屬性強制轉換提示。

protected $casts = ['modify' => 'boolean'];

我應該對集合運行某種關閉嗎? 我更喜歡使用以模型為中心的過程。

從laravel文檔中,方法setXXXAttribute就像這樣

public function setFirstNameAttribute($value)
    {
        $this->attributes['first_name'] = strtolower($value);
    }

所以我想你的代碼應該修改:

public function setModifyAttribute($value){
($value==="Modify"):$this->attributes['modify']=1?$this->attributes['modify']=0;

}

也許是錯的,祝你好運

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM