laravel获取器和修改器

laravel获取器和修改器

获取器

Eloquent 提供了一种便利的方法,可以在获取或设定属性时进行转换。要定义获取器,只要在模型里加入类似 getXxxxAttribute 的方法。注意方法名称应该使用驼峰式大小写命名,而对应的 database 字段名称是下划线分隔小写命名。

   访问器命名:前固定get,后固定Attribute,中间加字段名。
   比如:字段名为gender,则访问器为:getGenderAttribute。
   再如:字段名为user_name,则访问器为:getUserNameAttribute。

示例1:
原数据:

{
“id”: 1,
“name”: “小明”,
“email”: “333”
}

现在改变email添加“@qq.com”在User model里添加

//参数$value 是源字段值,可修改返回
    public function getEmailAttribute($value)
    {
        return $value.'@qq.com';
    }

结果如下:

{
“id”: 1,
“name”: “小明”,
“email”: “333@qq.com”
}

示例2:
我们也可以创建一个model里没有字段,用已有的数据字段进行整合,不过要进行数据追加。
首先在User medel 里添加

//将要添加字段追加到数据对象列表里去
protected $appends = ['describe'];

然后再创建一个新字段的获取器:

//创建一个虚拟字段
    public function getDescribeAttribute()
    {
        return $this->name.'的邮箱'.$this->email;
    }

结果:

{
“id”: 1,
“name”: “小明”,
“email”: “333@qq.com”,
“describe”: “小明的邮箱333@qq.com”
}

因为email 是修改后的数据所以describe取到的值包括@qq.com
如果想要用原数据:

public function getDescribeAttribute()
    {
        return $this->attributes['name'].'的邮箱'.$this->attributes['email'];
    }

结果:

{
“id”: 1,
“name”: “小明”,
“email”: “333@qq.com”,
“describe”: “小明的邮箱333”
}

修改器

修改器,相对于访问器,是在写入数据库的时候拦截,进行修改后,再写入。
修改器的命名方法和访问器一致,只不过是将get修改为set。如setXxxxAttribute的样子。
示例1:
当我们不确定用户输入的email 大小写时:
在User model里添加代码

	 //修改器,将邮箱改为小写
    public function setEmailAttribute($value)
    {
        $this->attributes['email'] = strtolower($value);
    }

在controller 里添加:

        $list = User::query()->find(1);
        $list->email = "EMAIL";
        $list->save();

结果:

{
“id”: 1,
“name”: “小明”,
“email”: “email@qq.com”,
“describe”: “小明的邮箱email”
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值