Laravel 8 在關(guān)聯(lián)之后鏈?zhǔn)教砑?orWhere 條件

2021-07-19 11:39 更新

如上所示,你可以在查詢關(guān)聯(lián)時自由添加其他約束。但是,在將 orWhere 子句鏈接到關(guān)聯(liá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ù)情況下,你可以使用 約束組 在括號中對條件檢查進行邏輯分組:

use Illuminate\Database\Eloquent\Builder;

$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) 


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號