Mutators and Attribute Casting
我有一个带有'修改'属性。 该模型使用set属性。这是因为存储保持为布尔值,但属性是通过选择来管理的(因为可用的FE选项是三态:[none | modify | access]其中没有'没有存储BE。
存储如下(mysql):
+-------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+-------+
| prop_id | int(10) unsigned | NO | PRI | NULL | |
| modify | tinyint(1) | NO | | 1 | |
+-------------+------------------+------+-----+---------+-------+
该模型使用以下mutator方法来翻译'修改'为真。
public function setModifyAttribute($value)
{
$this->attributes['modify'] = ($value === "modify");
}
为sync()传递的典型集合如下:
$properties =
Collection {
#items: array [
1 => array [
"modify" => "modify"
]
7 => array [
"modify" => "access"
]
]
}
然后我按如下方式调用属性的同步:
$this->properties()->sync($properties);
但是,未从sync()访问setModifyAttribute()。
或者,使用值' true'并且' false' sync()似乎忽略了属性转换提示。
protected $casts = ['modify' => 'boolean'];
我应该在集合上运行某种封闭吗?我更愿意使用以模型为中心的过程。
答案 0 :(得分:-3)
从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;
}
也许这是错的,祝你好运