高级篇 Laravel-EloquentORM

欢迎大家关注我的其他<a href ="http://blog.csdn.net/u014377963" >CSDN博客</a>和<a href ="http://www.jianshu.com/u/a9f9d36ab057">简书</a>,互相交流!

查询作用域#

全局作用域#

全局作用域允许你对给定模型的所有查询添加约束。使用全局作用域功能可以为模型的所有操作增加约束。

软删除功能实际上就是利用了全局作用域功能

实现一个全局作用域功能只需要定义一个实现Illuminate\Database\Eloquent\Scope接口的类,该接口只有一个方法apply,在该方法中增加查询需要的约束

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class AgeScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        return $builder->where('age', '>', 200);
    }
}

在模型的中,需要覆盖其boot方法,在该方法中增加addGlobalScope

<?php

namespace App;

use App\Scopes\AgeScope;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new AgeScope);
    }
}

添加全局作用域之后,User::all()操作将会产生如下等价sql

select * from `users` where `age` > 200

也可以使用匿名函数添加全局约束

static::addGlobalScope('age', function(Builder $builder) {
  $builder->where('age', '>', 200);
});

查询中要移除全局约束的限制,使用withoutGlobalScope方法

// 只移除age约束
User::withoutGlobalScope('age')->get();
User::withoutGlobalScope(AgeScope::class)->get();
// 移除所有约束
User::withoutGlobalScopes()->get();
// 移除多个约束
User::withoutGlobalScopes([FirstScope::class, SecondScope::class])->get();

本地作用域#

本地作用域只对部分查询添加约束,需要手动指定是否添加约束,在模型中添加约束方法,使用前缀scope

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Scope a query to only include popular users.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }

    /**
     * Scope a query to only include active users.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }
}

使用上述添加的本地约束查询,只需要在查询中使用scope前缀的方法,去掉scope前缀即可

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

本地作用域方法是可以接受参数的

public function scopeOfType($query, $type)
{
    return $query->where('type', $type);
}

调用的时候

$users = App\User::ofType('admin')->get();

事件#

Eloquent模型会触发下列事件

creating, created, updating, updated, saving, saved,deleting, deleted, restoring, restored

使用场景#

假设我们希望保存用户的时候对用户进行校验,校验通过后才允许保存到数据库,可以在服务提供者中为模型的事件绑定监听

<?php

namespace App\Providers;

use App\User;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        User::creating(function ($user) {
            if ( ! $user->isValid()) {
                return false;
            }
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

上述服务提供者对象中,在框架启动时会监听模型的creating事件,当保存用户之间检查用户数据的合法性,如果不合法,返回false,模型数据不会被持久化到数据。
返回false会阻止模型的save / update操作

序列化#

当构建JSON API的时候,经常会需要转换模型和关系为数组或者json。Eloquent提供了一些方法可以方便的来实现数据类型之间的转换。

转换模型/集合为数组 - toArray()#

$user = App\User::with('roles')->first();
return $user->toArray();

$users = App\User::all();
return $users->toArray();

转换模型为json - toJson()#

$user = App\User::find(1);
return $user->toJson();

$user = App\User::find(1);
return (string) $user;

隐藏属性#

有时某些字段不应该被序列化,比如用户的密码等,使用$hidden字段控制那些字段不应该被序列化

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['password'];
}

隐藏关联关系的时候,使用的是它的方法名称,不是动态的属性名

也可以使用$visible指定会被序列化的白名单

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be visible in arrays.
     *
     * @var array
     */
    protected $visible = ['first_name', 'last_name'];
}

有时可能需要某个隐藏字段被临时序列化,使用makeVisible方法

return $user->makeVisible('attribute')->toArray();

为json追加值#

有时需要在json中追加一些数据库中不存在的字段,使用下列方法,现在模型中增加一个get方法

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['is_admin'];

    /**
     * Get the administrator flag for the user.
     *
     * @return bool
     */
    public function getIsAdminAttribute()
    {
        return $this->attributes['admin'] == 'yes';
    }
}

方法签名为getXXXAttribute格式,然后为模型的$appends字段设置字段名。

Mutators#

在Eloquent模型中,AccessorMutator可以用来对模型的属性进行处理,比如我们希望存储到表中的密码字段要经过加密才行,我们可以使用Laravel的加密工具自动的对它进行加密。

Accessors & Mutators#

accessors#

要定义一个accessor,需要在模型中创建一个名称为getXxxAttribute的方法,其中的Xxx是驼峰命名法的字段名。

假设我们有一个字段是first_name,当我们尝试去获取first_name的值的时候,getFirstNameAttribute方法将会被自动的调用

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the user's first name.
     *
     * @param  string  $value
     * @return string
     */
    public function getFirstNameAttribute($value)
    {
        return ucfirst($value);
    }
}

在访问的时候,只需要正常的访问属性就可以

$user = App\User::find(1);
$firstName = $user->first_name;

mutators

创建mutatorsaccessorsl类似,创建名为setXxxAttribute的方法即可

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Set the user's first name.
     *
     * @param  string  $value
     * @return string
     */
    public function setFirstNameAttribute($value)
    {
        $this->attributes['first_name'] = strtolower($value);
    }
}

赋值方式

$user = App\User::find(1);
$user->first_name = 'Sally';

属性转换#

模型的$casts属性提供了一种非常简便的方式转换属性为常见的数据类型,在模型中,使用$casts属性定义一个数组,该数组的key为要转换的属性名称,value为转换的数据类型,当前支持integer, real, float, double, string, boolean, object, array,collection, date, datetime, 和 timestamp

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_admin' => 'boolean',
    ];
}

数组类型的转换时非常有用的,我们在数据库中存储json数据的时候,可以将其转换为数组形式。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'options' => 'array',
    ];
}

从配置数组转换的属性取值或者赋值的时候都会自动的完成json和array的转换

$user = App\User::find(1);  
$options = $user->options;
$options['key'] = 'value';
$user->options = $options;
$user->save();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容