亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

Laravel Eloquent ORM高級部分解析

瀏覽:45日期:2022-06-06 08:43:09
目錄
  • 查詢作用域
    • 全局作用域
    • 本地作用域
  • 事件
    • 使用場景
  • 序列化
    • 轉換模型/集合為數組 - toArray()
    • 轉換模型為json - toJson()
    • 隱藏屬性
    • 為json追加值
  • Mutators
    • Accessors & Mutators
    • accessors
    • mutators
    • 屬性轉換

查詢作用域

全局作用域

全局作用域允許你對給定模型的所有查詢添加約束。使用全局作用域功能可以為模型的所有操作增加約束。

軟刪除功能實際上就是利用了全局作用域功能

實現一個全局作用域功能只需要定義一個實現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的時候,經常會需要轉換模型和關系為數組或者jsonEloquent提供了一些方法可以方便的來實現數據類型之間的轉換。

轉換模型/集合為數組 - 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();

以上就是Laravel Eloquent ORM高級部分解析的詳細內容,更多關于Laravel Eloquent ORM解析的資料請關注其它相關文章!

標簽: PHP
主站蜘蛛池模板: ssss国产在线观看 | 免费看片网址 | 欧美人妖猛交 | 日本特黄特色大片免费播放视频 | 成人淫片 | 久久天天综合 | 免费在线观看a级片 | 亚洲国产精品成人久久 | 免费看黄色片网站 | 国产精品一区二区三区久久 | 九九99在线视频 | 妇女自拍偷自拍亚洲精品 | 国产v综合v亚洲欧美大另类 | 国产久视频观看 | 色系视频在线观看免费观看 | 久久国产视频网 | 三级黄色一级视频 | 天天天色 | 国模私拍福利一区二区 | 免费国产黄 | 国产在线观看网站 | 黄色一级片子 | 色片网址| 国产日韩亚洲欧美 | 日韩乱淫| 成人黄色激情网站 | 麻豆传媒在线完整视频 | 美国三级在线 | 一级黄色片免费播放 | 国产成人精品曰本亚洲78 | 日本中文字幕有码 | 深夜国产一区二区三区在线看 | 激情免费网站 | 精品毛片 | 成人毛片国产a | 国产在线视频网站 | 免费超爽大片黄 | 免费一级特黄特色大片∵黄 | 女人与zzzxxxx0oo0 | 香蕉福利视频 | 毛片毛片免费看 |