20個Laravel Eloquent 使用技巧

西門族長發表於2018-04-17

轉載自 Laravel-news

1、自增、自減

    //常規寫法
    $article = Article::find($article_id);
    $article->read_count++;
    $article->save();
    
    //eloquent寫法-1
    $article = Article::find($article_id);
    $article->increment('read_count');
    
    //eloquent寫法-2 鏈式寫法
    Article::find($article_id)->increment('read_count');
    Article::find($article_id)->increment('read_count', 10); // +10
    Product::find($produce_id)->decrement('stock'); // -1
複製程式碼

2、條件式方法 XorY methods

  • findOrFail(): 查詢不到的時候直接報錯
    $user = User::find($id);
    if (!$user) { abort (404); }
    //以上程式碼等同於
    $user = User::findOrFail($id);
複製程式碼
  • firstOrCreate():使用給定的欄位及其值在資料庫中查詢記錄。如果在資料庫中找不到模型,則將使用第一個引數中的屬性以及可選的第二個引數中的屬性插入記錄
    // 通過 name 屬性檢索航班,當結果不存在時建立它...
    $flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);

    // 通過 name 屬性檢索航班,當結果不存在的時候用 name 屬性和 delayed 屬性去建立它
    $flight = App\Flight::firstOrCreate(
        ['name' => 'Flight 10'], ['delayed' => 1]
    );
複製程式碼
  • firstOrNew():用法和firstOrCreate()一樣,但是firstOrNew()只是例項化一個物件,如果需要持久化則需要save()儲存
  • updateOrCreate(): 更新現有模型或建立新模型(如果不存在),同firstOrCreate()

3、Modelboot()方法

    /**
     * 基類:新增的時候自動將`uuid`欄位用`Uuid`生成器填充
     */
    class BaseModel extends Model
    {
        public static function boot()
        {
            parent::boot();
            self::creating(function ($model) {
                $model->uuid = (string)Uuid::generate();
            });
        }
    }
    
    /**
     * 使用者模型:修改的時候設定額外的操作
     */
    class User extends BaseModel
    {
        public static function boot()
        {
            parent::boot();
            static::updating(function($model)
            {
                // do some logging
                // override some property like $model->something = transform($something);
            });
        }
    }
複製程式碼

4、關聯新增額外條件並設定排序Relationship with conditions and ordering

    //通常的做法,關聯使用者模型
    public function users() {
        return $this->hasMany('App\User');    
    }

    //關聯已經批准並用`email`排序的使用者模型
    public function approvedUsers() {
        return $this->hasMany('App\User')->where('approved', 1)->orderBy('email');
    }
複製程式碼

5、Model類屬性 Model properties: timestamps, appends etc.

    class User extends Model {
        //經常用到的屬性
        protected $table = 'users';
        protected $fillable = ['email', 'password']; // which fields can be filled with User::create()
        protected $dates = ['created_at', 'deleted_at']; // which fields will be Carbon-ized
        protected $appends = ['field1', 'field2']; // additional values returned in JSON
        
        //其他很有用的屬性
        protected $primaryKey = 'uuid'; // it doesn't have to be "id"
        protected $keyType = 'string'; //設定主鍵欄位型別 default `int`
        public $incrementing = false; // and it doesn't even have to be auto-incrementing!
        protected $perPage = 25; // Yes, you can override pagination count PER MODEL (default 15)
        const CREATED_AT = 'created_at';
        const UPDATED_AT = 'updated_at'; // Yes, even those names can be overridden
        public $timestamps = false; // or even not used at all
    }
複製程式碼

6、用find方法查詢多條記錄Find multiple entries

    //find常用用法
    $user = User::find(1);
    //find其實也接收 陣列 為引數
    $users = User::find([1,2,3]);
複製程式碼

7、whereX魔術方法

    //where欄位名:欄位名第一字母大寫
    $users = User::whereApproved(1)->get(); //等同於 $users = User::where('approved', 1)->get();
    User::whereDate('created_at', date('Y-m-d'));
    User::whereDay('created_at', date('d'));
    User::whereMonth('created_at', date('m'));
    User::whereYear('created_at', date('Y'));
複製程式碼

8、Order by relationship

場景:論壇很多帖子topic,需要按有最新發言post的來排序

    //帖子關聯最新的發言
    public function latestPost()
    {
        return $this->hasOne(\App\Post::class)->latest();
    }
    $users = Topic::with('latestPost')->get()->sortByDesc('latestPost.created_at');
複製程式碼

9、Eloquent::when()別再寫那麼多的if-else

    //通常的寫法
    if (request('filter_by') == 'likes') {
        $query->where('likes', '>', request('likes_amount', 0));
    }
    if (request('filter_by') == 'date') {
        $query->orderBy('created_at', request('ordering_rule', 'desc'));
    }
    
    //Eloquent::when()寫法
    $query = Author::query();
    $query->when(request('filter_by') == 'likes', function ($q) {
        return $q->where('likes', '>', request('likes_amount', 0));
    });
    $query->when(request('filter_by') == 'date', function ($q) {
        return $q->orderBy('created_at', request('ordering_rule', 'desc'));
    });
    //可以傳遞引數
    $query = User::query();
    $query->when(request('role', false), function ($q, $role) { 
        return $q->where('role_id', $role);
    });
    $authors = $query->get();
複製程式碼

10、BelongsTo Default Models

    //blade:如果 author 被刪了就會報錯
    {{ $post->author->name }}
    
    //設定 預設Model 避免以上錯誤
    public function author()
    {
        return $this->belongsTo('App\Author')->withDefault([
            'name' => 'Guest Author'
        ]);
    }
複製程式碼

11、Order by Mutator : 藉助集合collect->sortBy方法

    function getFullNameAttribute()
    {
      return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
    }
    //錯誤寫法
    $clients = Client::orderBy('full_name')->get(); // doesn't work
    //正確寫法,藉助collect的sortBy方法
    $clients = Client::get()->sortBy('full_name'); // works!
複製程式碼

12、Default ordering in global scope

    protected static function boot()
    {
        parent::boot();
    
        // Order by name ASC
        static::addGlobalScope('order', function (Builder $builder) {
            $builder->orderBy('name', 'asc');
        });
    }
複製程式碼

13、 Raw query methods

    // whereRaw
    $orders = DB::table('orders')
        ->whereRaw('price > IF(state = "TX", ?, 100)', [200])
        ->get();
    
    // havingRaw
    Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();
    
    // orderByRaw
    User::where('created_at', '>', '2016-01-01')
      ->orderByRaw('(updated_at - created_at) desc')
      ->get();
複製程式碼

14、Replicate: make a copy of a row

這是複製某條記錄最好的方法

    $task = Tasks::find(1);
    $newTask = $task->replicate();
    $newTask->save();
複製程式碼

15、Chunk() method for big tables

Collect集合方法:需要輸出大量記錄的時候用chunk

    User::chunk(100, function ($users) {
        foreach ($users as $user) {
            // ...
        }
    });
複製程式碼

16、Create additional things when creating a model

artisan命令生成model的時候一起生成controller -rmigration file

    php artisan make:model Company -mcr
複製程式碼

17、Override updated_at when saving

save()方法接收額外的引數

    $product = Product::find($id);
    $product->updated_at = '2019-01-01 10:00:00';
    $product->save(['timestamps' => false]);
複製程式碼

18、What is the result of an update()?

    //返回更新的記錄數
    $result = $products->whereNull('category_id')->update(['category_id' => 2]);
複製程式碼

19、where引數分組

    //... WHERE (gender = 'Male' and age >= 18) or (gender = 'Female' and age >= 65) 的 Eloquent 寫法
    $q->where(function ($query) {
        $query->where('gender', 'Male')
            ->where('age', '>=', 18);
    })->orWhere(function($query) {
        $query->where('gender', 'Female')
            ->where('age', '>=', 65); 
    })
複製程式碼

20、orWhere with multiple parameters

    $q->orWhere(['b' => 2, 'c' => 3]);
複製程式碼

相關文章