laravel ORM 的setAttributes 与 getAttributes

来源:互联网 发布:.top域名为什么便宜 编辑:程序博客网 时间:2024/06/07 00:51

参考 laravel 例子
访问器&修改器

    有时候,需要添加数据库中没有相应的字段到数组中,要实现这个,首先要定义一个访问器 ; 定义好访问器后,添加字段名到模型的appends属性 ; 以下例子实现 通过处理 最后登陆时间 字段追加 未登陆天数 属性 :

  • 例1
namespace App\Models;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)) . '天' ;    }}
namespace App\Http\Controllers;use DB;use App\Models\Users;class UserController extends BaseController{    public function getTest()    {        $res = Users::find(1);        // $res = OpadmUsers::find(1)->had_not_login_days;  50天        dd($res)    }}

打印结果可以看到 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);  // '该用户长时间未登录'

定义修改器:要定义一个修改器,需要在模型中定义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
原创粉丝点击