laravel实现Model的setAttribute、getAttribute、scopeQuery方法

版权声明:版权归qq175023117所有 https://blog.csdn.net/qq175023117/article/details/84882179

首先要定义一个Model

1.getAttribute的实现

getFooAttribute在模型上创建一个方法,其中Foo包含您要访问的列的“studly”外壳名称。在这个例子中,我们将为first_name属性定义一个访问器。尝试检索sex属性值时,Eloquent会自动调用访问者:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function getSexAttribute($sex)
    {
        if ($sex == 1) return '男';
        if ($sex == 2) return '女';
        return '未知';
    }
}

查询出来模型以后获取sex,将是男或者女或者未知 

$user = App\User::find(1);
$sex = $user->sex;
dd($sex); // 男

2.setAttribute的实现

getFooAttribute在模型上创建一个方法,其中Foo包含您要访问的列的“studly”外壳名称。在这个例子中,我们将为first_name属性定义一个访问器。尝试检索sex属性值时,Eloquent会自动调用访问者:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function setSexAttribute($sex)
    {
       $this->attributes['sex'] = $sex;
    }
}

查询出来模型以后获取sex,将是男或者女或者未知 

$user = App\User::find(1);
$user->sex = '我是sex';
dd($user->sex);   // 我是sex

3.scopeQuery的实现

本地范围允许您定义可在整个应用程序中轻松重用的常见约束集。例如,您可能需要经常检索所有被视为“受欢迎”的用户。要定义范围,请使用Eloquent模型方法作为前缀scope。范围应始终返回查询构建器实例:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function scopeSex($query)
    {
        return $query->where('sex', 1);
    }
}

 定义后,可以在查询模型时调用该方法。但是,scope调用方法时不应包含前缀。您甚至可以将调用链接到各种范围,如:

$users = App\User::sex()->orderBy('created_at')->get();

纯原创,希望可以对大家有帮助,如有疑问,欢迎评论 

猜你喜欢

转载自blog.csdn.net/qq175023117/article/details/84882179
今日推荐