Mutators and Attribute Casting
I have a model with a 'modify' attribute. The model uses a set attribute. 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.
Storage is as follows (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.
public function setModifyAttribute($value)
{
$this->attributes['modify'] = ($value === "modify");
}
A typical collection being passed over for sync() is as follows:
$properties =
Collection {
#items: array [
1 => array [
"modify" => "modify"
]
7 => array [
"modify" => "access"
]
]
}
I am then calling sync for the properties as follows:
$this->properties()->sync($properties);
However, the setModifyAttribute() is not being accessed from sync().
Alternatively, using values 'true' and 'false' sync() appears to be ignoring the Attribute Casting hints.
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.