繁体   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