属性访问器
获取属性时使用,例如想要增加一个模型中不存在的属性 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
更多精彩内容:各种AI课程、技能课程、黑科技软件、网站小程序源码、副业小项目、PPT模板等精品素材、电商课程、推广引流课程等,尽在 天边资源网 。