【原创】Laravel 属性修改器

属性访问器

获取属性时使用,例如想要增加一个模型中不存在的属性 depth,该字段是由 full_name 计算得出,代码如下:

class CModel extends Model
{
    public function getDepthAttribute()
    {
       return count(explode('>', $this->full_name));
    }
}

$aa = CModel::find(1); // $aa->full_name='Baa>Caa';
$aa->depth; // 2

属性修改器

设置属性时使用,例如想要将 full_name 字段在设置时进行全部小写的转换,代码如下:

class CModel extends Model
{
    public function setFullNameAttribute($value)
    {
       $this->attributes['full_name'] = strtolower($value);
    }
}

$aa = CModel::find(1);
$aa->full_name = 'Baa>Css';
$aa->full_name // 输出 baa>css
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注