laravel ORM 的setAttributes 与 getAttributes
|
有时候,需要添加数据库中没有相应的字段到数组中,要实现这个,首先要定义一个访问器 ; 定义好访问器后,添加字段名到模型的appends属性 ; 以下例子实现 通过处理 最后登陆时间 字段追加 未登陆天数 属性 : 例1 namespace AppModels; class Users extends BaseModel { /** * [$connection 数据库链接] * @var string */ protected $connection = 'mysql'; /** * [$table 数据表] * @var string */ protected $table = 'users'; // 追加未登录天数属性 protected $appends = ['had_not_login_days']; // 表里没有的字段 // 处理没登陆天数 public function getHadNotLoginDaysAttribute() { $login = $this->attributes['last_login_time']; // $this->attributes表的字段属性 $create = $this->attributes['created_at']; if( $login > 0) { $time = time() - $login; // 有最后登陆时间 } else { $time = time() - $create; // 没,创建时间 } return intval(floor($time / 86400)) . '天' ; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 namespace AppHttpControllers; use DB; use AppModelsUsers; class UserController extends BaseController { public function getTest() { $res = Users::find(1); // $res = OpadmUsers::find(1)->had_not_login_days; 50天 dd($res) } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 打印结果可以看到 appends 属性: 例2 // 在模型里定义 public function getLastLoginTimeAttribute($value) { if( time() - $value > 30 * 86400 ) return $this->attributes['last_login_time'] = '该用户长时间未登录'; } // 获取数据 $res = OpadmUsers::find(1)->last_login_time; dd($res); // '该用户长时间未登录' 1 2 3 4 5 6 7 8 9 10 11 定义修改器:要定义一个修改器,需要在模型中定义setFooAttribute方法,其中Foo是你想要访问的字段(使用驼峰式命名规则)。接下来让我们为last_login_time属性定义一个修改器,当我们为模型上的last_login_time赋值时该修改器会被自动调用: 例3: 修改性别 // 在模型 public function setSexAttribute($value) { if( $value == '男' ) $this->attributes['sex'] = 1; else $this->attributes['sex'] = 0; } // 控制器 $res = OpadmUsers::find(1); $res->sex = '男'; $res->save(); // 写入数据库 sex = 1 --------------------- 作者:小Z笔记 来源:CSDN 原文:https://blog.csdn.net/mathphp/article/details/78619043 版权声明:本文为博主原创文章,转载请附上博文链接! (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
