laravel實(shí)戰(zhàn)代碼-創(chuàng)建更高級的 where 子句
laravel實(shí)戰(zhàn)代碼-講解1-laravel查詢構(gòu)造器之參數(shù)分組:創(chuàng)建更高級的 where 子句-用where約束組而不是用orwhere

各位看官,上午好,大家在進(jìn)行多where約束時候如何寫的呢?比如在進(jìn)行列表分頁查詢帶條件時候.
是 where->orwhere嗎?
這里告訴大家,我們可以更見美觀,方便的,隨心所欲的寫where子句.
下面我們開講:
這里我們講一個參數(shù)分組(約束組)的概念.
首先,參數(shù)分組.
有時候你需要創(chuàng)建更高級的 where 子句,例如「where exists」或者嵌套的參數(shù)分組。Laravel 的查詢構(gòu)造器也能夠處理這些。下面,讓我們看一個在括號中進(jìn)行分組約束的例子:
$users = DB::table('users')
? ? ? ? ? ->where('name', '=', 'John')
? ? ? ? ? ->where(function ($query) {
? ? ? ? ? ? ? $query->where('votes', '>', 100)
? ? ? ? ? ? ? ? ? ? ->orWhere('title', '=', 'Admin');
? ? ? ? ? })
? ? ? ? ? ->get();
你可以看到,通過一個 Closure 寫入 where 方法構(gòu)建一個查詢構(gòu)造器 來約束一個分組。這個 Closure 接收一個查詢實(shí)例,你可以使用這個實(shí)例來設(shè)置應(yīng)該包含的約束。上面的例子將生成以下 SQL:
select * from users where name = 'John' and (votes > 100 or title = 'Admin')
{提示} 你應(yīng)該用 orWhere 調(diào)用這個分組,以避免應(yīng)用全局作用出現(xiàn)意外。
2. 那么在模型關(guān)聯(lián)中,我們會有這種情況使用到約束組
在關(guān)聯(lián)之后鏈?zhǔn)教砑?orWhere?條件
你可以在查詢關(guān)聯(lián)時自由添加其他約束。但是,在將 orWhere 子句鏈接到關(guān)聯(lián)時要小心,因?yàn)?orWhere 子句將在邏輯上與關(guān)聯(lián)約束處于同一級別:
$user->posts()
? ? ? ?->where('active', 1)
? ? ? ?->orWhere('votes', '>=', 100)
? ? ? ?->get();
// select * from posts
// where user_id = ? and active = 1 or votes >= 100
在大多數(shù)情況下,你可以使用約束組 在括號中對條件檢查進(jìn)行邏輯分組:
$user->posts()
? ? ? ?->where(function (Builder $query) {
? ? ? ? ? ?return $query->where('active', 1)
? ? ? ? ? ? ? ? ? ? ? ? ->orWhere('votes', '>=', 100);
? ? ? ?})
? ? ? ?->get();
// select * from posts
// where user_id = ? and (active = 1 or votes >= 100)
3. 在哪些情況下我們還是用where約束組而不是用orwhere?
尤其你是多個參數(shù)傳遞進(jìn)來,我們需要進(jìn)行判斷時候
例如:我們在進(jìn)行列表時候,分頁,查詢條件.?
我們合起來可以這么寫
// ? ? ? ?直接導(dǎo)入request 進(jìn)行查詢
? ? ? ?$user = User::orderBy('user_id','asc')
? ? ? ? ? ?->where(function($query) use($request){
? ? ? ? ? ? ? ?$username = $request->input('username');
? ? ? ? ? ? ? ?$email = $request->input('email');
? ? ? ? ? ? ? ?if(!empty($username)){
? ? ? ? ? ? ? ? ? ?$query->where('username','like','%'.$username.'%');
? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?if(!empty($email)){
? ? ? ? ? ? ? ? ? ?$query->where('username','like','%'.$email.'%');
? ? ? ? ? ? ? ?}
? ? ? ? ? ?})
? ? ? ? ? ?->paginate($request->input('num')?$request->input('num'):3);
? ? ? ?// 如何看這段多參數(shù)查詢列表的 $query對象
? ? ? ?// 答 ?這是查詢構(gòu)造器中的參數(shù)分組
// ? ? ? ?一個在括號中進(jìn)行分組約束的例子
// ? ? ? ?此處我們通過閉包.來得到query 傳入$request參數(shù)
// ? ? ? ?來進(jìn)行處理,最后在閉包中寫邏輯,直接得到我們一整個query對象
// ? ? ? ?進(jìn)而傳遞給where
看完上面這個代碼,是不是感覺舒服很多,代碼也好看了.
ps:這個閉包后跟了一個use.解釋如下:?
閉包的語法很簡單,需要注意的關(guān)鍵字就只有use,use意思是連接閉包和外界變量。
匿名函數(shù)中的use,其作用就是從父作用域繼承變量。
引用文檔:
https://learnku.com/docs/laravel/6.x/queries/5171#parameter-grouping
https://learnku.com/docs/laravel/6.x/eloquent-relationships/5177