W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
在查詢時,可能需要將關(guān)聯(lián)記錄是否存在作為條件。例如,查出至少有一條評論的文章。可以通過向 has
和 orHas
方法傳遞關(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();
如果需要更多功能,可以使用 whereHas
和 orWhereHas
方法將「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();
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: