[PHP] LaravelEloquentORM高级部分解析

2119 0
王子 2022-11-6 08:38:31 | 显示全部楼层 |阅读模式
目录

    查询作用域
      全局作用域本地作用域
    事件
      使用场景
    序列化
      转换模型/集合为数组 - toArray()转换模型为json - toJson()隐藏属性为json追加值
    Mutators
      Accessors & Mutatorsaccessorsmutators属性转换



查询作用域


全局作用域

全局作用域允许你对给定模型的所有查询添加约束。使用全局作用域功能可以为模型的所有操作增加约束。
软删除功能实际上就是利用了全局作用域功能
实现一个全局作用域功能只需要定义一个实现Illuminate\Database\Eloquent\Scope接口的类,该接口只有一个方法apply,在该方法中增加查询需要的约束
  1. <?php
  2. namespace App\Scopes;
  3. use Illuminate\Database\Eloquent\Scope;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\Builder;
  6. class AgeScope implements Scope
  7. {
  8.     /**
  9.      * Apply the scope to a given Eloquent query builder.
  10.      *
  11.      * @param  \Illuminate\Database\Eloquent\Builder  $builder
  12.      * @param  \Illuminate\Database\Eloquent\Model  $model
  13.      * @return void
  14.      */
  15.     public function apply(Builder $builder, Model $model)
  16.     {
  17.         return $builder->where('age', '>', 200);
  18.     }
  19. }
复制代码
在模型的中,需要覆盖其boot方法,在该方法中增加addGlobalScope
<?phpnamespace 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
  1. select * from `users` where `age` > 200
复制代码
也可以使用匿名函数添加全局约束
  1.     static::addGlobalScope('age', function(Builder $builder) {
  2.       $builder->where('age', '>', 200);
  3.     });
复制代码
查询中要移除全局约束的限制,使用withoutGlobalScope方法
  1.     // 只移除age约束
  2.     User::withoutGlobalScope('age')->get();
  3.     User::withoutGlobalScope(AgeScope::class)->get();
  4.     // 移除所有约束
  5.     User::withoutGlobalScopes()->get();
  6.     // 移除多个约束
  7.     User::withoutGlobalScopes([FirstScope::class, SecondScope::class])->get();
复制代码
本地作用域

本地作用域只对部分查询添加约束,需要手动指定是否添加约束,在模型中添加约束方法,使用前缀scope
  1.     <?php
  2.     namespace App;
  3.     use Illuminate\Database\Eloquent\Model;
  4.     class User extends Model
  5.     {
  6.         /**
  7.          * Scope a query to only include popular users.
  8.          *
  9.          * @return \Illuminate\Database\Eloquent\Builder
  10.          */
  11.         public function scopePopular($query)
  12.         {
  13.             return $query->where('votes', '>', 100);
  14.         }
  15.         /**
  16.          * Scope a query to only include active users.
  17.          *
  18.          * @return \Illuminate\Database\Eloquent\Builder
  19.          */
  20.         public function scopeActive($query)
  21.         {
  22.             return $query->where('active', 1);
  23.         }
  24.     }
复制代码
使用上述添加的本地约束查询,只需要在查询中使用scope前缀的方法,去掉scope前缀即可
  1. $users = App\User::popular()->active()->orderBy('created_at')->get();
  2. // 本地作用域方法是可以接受参数的
  3. public function scopeOfType($query, $type)
  4. {
  5.     return $query->where('type', $type);
  6. }
  7. // 调用的时候
  8. $users = App\User::ofType('admin')->get();
复制代码
事件

Eloquent模型会触发下列事件
creating`, `created`, `updating`, `updated`, `saving`, `saved`,`deleting`, `deleted`, `restoring`, `restored

使用场景

假设我们希望保存用户的时候对用户进行校验,校验通过后才允许保存到数据库,可以在服务提供者中为模型的事件绑定监听
  1. <?php
  2. namespace App\Providers;
  3. use App\User;
  4. use Illuminate\Support\ServiceProvider;
  5. class AppServiceProvider extends ServiceProvider
  6. {
  7.     /**
  8.      * Bootstrap any application services.
  9.      *
  10.      * @return void
  11.      */
  12.     public function boot()
  13.     {
  14.         User::creating(function ($user) {
  15.             if ( ! $user->isValid()) {
  16.                 return false;
  17.             }
  18.         });
  19.     }
  20.     /**
  21.      * Register the service provider.
  22.      *
  23.      * @return void
  24.      */
  25.     public function register()
  26.     {
  27.         //
  28.     }
  29. }
复制代码
上述服务提供者对象中,在框架启动时会监听模型的creating事件,当保存用户之间检查用户数据的合法性,如果不合法,返回false,模型数据不会被持久化到数据。
返回false会阻止模型的save / update操作

序列化

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

转换模型/集合为数组 - toArray()
  1.     $user = App\User::with('roles')->first();
  2.     return $user->toArray();
  3.     $users = App\User::all();
  4.     return $users->toArray();
复制代码
转换模型为json - toJson()
  1.     $user = App\User::find(1);
  2.     return $user->toJson();
  3.     $user = App\User::find(1);
  4.     return (string) $user;
复制代码
隐藏属性

有时某些字段不应该被序列化,比如用户的密码等,使用$hidden字段控制那些字段不应该被序列化
  1.     <?php
  2.     namespace App;
  3.     use Illuminate\Database\Eloquent\Model;
  4.     class User extends Model
  5.     {
  6.         /**
  7.          * The attributes that should be hidden for arrays.
  8.          *
  9.          * @var array
  10.          */
  11.         protected $hidden = ['password'];
  12.     }
复制代码
隐藏关联关系的时候,使用的是它的方法名称,不是动态的属性名
也可以使用$visible指定会被序列化的白名单
  1.     <?php
  2.     namespace App;
  3.     use Illuminate\Database\Eloquent\Model;
  4.     class User extends Model
  5.     {
  6.         /**
  7.          * The attributes that should be visible in arrays.
  8.          *
  9.          * @var array
  10.          */
  11.         protected $visible = ['first_name', 'last_name'];
  12.     }
  13. // 有时可能需要某个隐藏字段被临时序列化,使用`makeVisible`方法
  14. return $user->makeVisible('attribute')->toArray();
复制代码
为json追加值

有时需要在json中追加一些数据库中不存在的字段,使用下列方法,现在模型中增加一个get方法
  1.     <?php
  2.     namespace App;
  3.     use Illuminate\Database\Eloquent\Model;
  4.     class User extends Model
  5.     {
  6.         /**
  7.          * The accessors to append to the model's array form.
  8.          *
  9.          * @var array
  10.          */
  11.         protected $appends = ['is_admin'];
  12.         /**
  13.          * Get the administrator flag for the user.
  14.          *
  15.          * @return bool
  16.          */
  17.         public function getIsAdminAttribute()
  18.         {
  19.             return $this->attributes['admin'] == 'yes';
  20.         }
  21.     }
复制代码
方法签名为getXXXAttribute格式,然后为模型的$appends字段设置字段名。

Mutators

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

Accessors & Mutators


accessors

要定义一个accessor,需要在模型中创建一个名称为getXxxAttribute的方法,其中的Xxx是驼峰命名法的字段名。
假设我们有一个字段是first_name,当我们尝试去获取first_name的值的时候,getFirstNameAttribute方法将会被自动的调用
  1.     <?php
  2.     namespace App;
  3.     use Illuminate\Database\Eloquent\Model;
  4.     class User extends Model
  5.     {
  6.         /**
  7.          * Get the user's first name.
  8.          *
  9.          * @param  string  $value
  10.          * @return string
  11.          */
  12.         public function getFirstNameAttribute($value)
  13.         {
  14.             return ucfirst($value);
  15.         }
  16.     }
  17. // 在访问的时候,只需要正常的访问属性就可以
  18.     $user = App\User::find(1);
  19.     $firstName = $user->first_name;
复制代码
mutators

创建mutators与accessorsl类似,创建名为setXxxAttribute的方法即可
  1.     <?php
  2.     namespace App;
  3.     use Illuminate\Database\Eloquent\Model;
  4.     class User extends Model
  5.     {
  6.         /**
  7.          * Set the user's first name.
  8.          *
  9.          * @param  string  $value
  10.          * @return string
  11.          */
  12.         public function setFirstNameAttribute($value)
  13.         {
  14.             $this->attributes['first_name'] = strtolower($value);
  15.         }
  16.     }
  17. // 赋值方式
  18.     $user = App\User::find(1);
  19.     $user->first_name = 'Sally';
复制代码
属性转换

模型的$casts属性提供了一种非常简便的方式转换属性为常见的数据类型,在模型中,使用$casts属性定义一个数组,该数组的key为要转换的属性名称,value为转换的数据类型,当前支持integer, real, float, double, string, boolean, object, array,collection, date, datetime, 和 timestamp。
  1.     <?php
  2.     namespace App;
  3.     use Illuminate\Database\Eloquent\Model;
  4.     class User extends Model
  5.     {
  6.         /**
  7.          * The attributes that should be casted to native types.
  8.          *
  9.          * @var array
  10.          */
  11.         protected $casts = [
  12.             'is_admin' => 'boolean',
  13.         ];
  14.     }
复制代码
数组类型的转换时非常有用的,我们在数据库中存储json数据的时候,可以将其转换为数组形式。
  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class User extends Model
  5. {
  6.     /**
  7.      * The attributes that should be casted to native types.
  8.      *
  9.      * @var array
  10.      */
  11.     protected $casts = [
  12.         'options' => 'array',
  13.     ];
  14. }
  15. // 从配置数组转换的属性取值或者赋值的时候都会自动的完成json和array的转换
  16. $user = App\User::find(1);  
  17. $options = $user->options;
  18. $options['key'] = 'value';
  19. $user->options = $options;
  20. $user->save();
复制代码
以上就是Laravel Eloquent ORM高级部分解析的详细内容,更多关于Laravel Eloquent ORM解析的资料请关注中国红客联盟其它相关文章!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行