范圍查詢

2018-02-24 15:52 更新

定義范圍查詢

范圍查詢可以讓您輕松的重復(fù)利用模型的查詢邏輯。要設(shè)定范圍查詢,只要定義有 scope 前綴的模型方法:

class User extends Model {
    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }
    public function scopeWomen($query)
    {
        return $query->whereGender('W');
    }
}

使用范圍查詢

$users = User::popular()->women()->orderBy('created_at')->get();

動(dòng)態(tài)范圍查詢

有時(shí)您可能想要定義可接受參數(shù)的范圍查詢方法。只要把參數(shù)加到方法里:

class User extends Model {
    public function scopeOfType($query, $type)
    {
        return $query->whereType($type);
    }
}

然后把參數(shù)值傳到范圍查詢方法調(diào)用里:

$users = User::ofType('member')->get();
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)