在模型中修改数据保存以及读取的格式
代码示例,数据表posts的模型
getTagsAttribute() 方法表示修改读取tags字段的格式
setTagsAttribute() 方法表示修改保存tags字段时的数据格式
class Post extends Model
{
public function getTagsAttribute($value)
{
return explode(',', $value);
}
public function setTagsAttribute($value)
{
$this->attributes['tags'] = implode(',', $value);
}
}
Laravel 5新添加的属性转化功能能让这些变得更为容易些。在模型类文件中的$casts属性里,写上那些需要转换的属性(对应的就是数据表字段)及其对应目标类型:
protected $casts = [ 'age' => 'integer' ];