Laravel 8 查詢已存在的關(guān)聯(lián)

2021-07-19 11:39 更新

在查詢時,可能需要將關(guān)聯(lián)記錄是否存在作為條件。例如,查出至少有一條評論的文章。可以通過向 hasorHas 方法傳遞關(guān)聯(lián)名稱實現(xiàn):

// 查出至少有一條評論的文章...
$posts = App\Models\Post::has('comments')->get(); 

也可以指定運算符和數(shù)量來進一步自定義查詢:

// 查出至少有三條評論的文章...
$posts = App\Models\Post::has('comments', '>=', 3)->get(); 

也可以用「點」語法構(gòu)造嵌套的 has 語句。例如,查出至少有一條評論和投票的文章:

// 查出至少有一條帶投票評論的文章...
$posts = App\Models\Post::has('comments.votes')->get(); 

如果需要更多功能,可以使用 whereHasorWhereHas 方法將「where」條件放到 has 查詢上。這些方法允許你向關(guān)聯(lián)加入自定義約束,比如檢查評論內(nèi)容:

use Illuminate\Database\Eloquent\Builder;

// 獲取至少帶有一條評論內(nèi)容包含 foo% 關(guān)鍵詞的文章...
$posts = App\Models\Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', 'foo%');
})->get();

// 獲取至少帶有十條評論內(nèi)容包含 foo% 關(guān)鍵詞的文章...
$posts = App\Models\Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', 'foo%');
}, '>=', 10)->get();
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號