[英]Laravel 5.4: Eloquent sync() not using model's mutator or attribute casting?
Mutators and Attribute Casting 变量和属性转换
I have a model with a 'modify' attribute. 我有一个带有“修改”属性的模型。 The model uses a set attribute. 该模型使用set属性。 This is because the storage is held as boolean, but the attribute is managed via a select (because the FE options available are three-state: [none | modify | access ] where 'none' is not stored BE. 这是因为存储被保存为布尔值,但是该属性是通过选择进行管理的(因为可用的FE选项处于三种状态:[无|修改|访问],其中“无”不存储在BE中。
Storage is as follows (mysql): 存储如下(mysql):
+-------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+-------+
| prop_id | int(10) unsigned | NO | PRI | NULL | |
| modify | tinyint(1) | NO | | 1 | |
+-------------+------------------+------+-----+---------+-------+
The model uses the following mutator method to translate 'modify' to true. 该模型使用以下mutator方法将“ modify”转换为true。
public function setModifyAttribute($value)
{
$this->attributes['modify'] = ($value === "modify");
}
A typical collection being passed over for sync() is as follows: 传递给sync()的典型集合如下:
$properties =
Collection {
#items: array [
1 => array [
"modify" => "modify"
]
7 => array [
"modify" => "access"
]
]
}
I am then calling sync for the properties as follows: 然后,我为属性调用sync,如下所示:
$this->properties()->sync($properties);
However, the setModifyAttribute() is not being accessed from sync(). 但是,不会从sync()访问setModifyAttribute()。
Alternatively, using values 'true' and 'false' sync() appears to be ignoring the Attribute Casting hints. 或者,使用值'true'和'false'sync()似乎忽略了属性强制转换提示。
protected $casts = ['modify' => 'boolean'];
Should I run some sort of closure over the collection instead? 我应该对集合运行某种关闭吗? I would prefer to use a model-centric process. 我更喜欢使用以模型为中心的过程。
from the laravel documentation the method setXXXAttribute is just like this 从laravel文档中,方法setXXXAttribute就像这样
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}
so i guess your code should be modified : 所以我想你的代码应该修改:
public function setModifyAttribute($value){
($value==="Modify"):$this->attributes['modify']=1?$this->attributes['modify']=0;
}
maybe it is wrong ,good luck 也许是错的,祝你好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.