我有下表
帖子
- ID
- 姓名
類別
- ID
- 姓名
category_post
- post_id
- category_id
后.php
public function Category()
{
return $this->belongsToMany(Category::class);
}
分類.php
public function posts()
{
return $this->belongsToMany(Post::class);
}
一個帖子可能包含許多類別。
我想在最少的資料庫查詢中查詢與任何給定帖子的類別相關的所有帖子。
例如,如果一個帖子屬于三個類別,我想獲取與這三個類別相關的所有帖子。我可以在 4 個資料庫查詢中實作這一點,如下所示。
$post = Post::find(1);
$categoryIds = $post->category()->pluck('id');
$postIds = DB::table('category_post')
->whereIn('category_id', $categoryIds)
->pluck('post_id')
->unique();
$relatedPosts = DB::table('posts')
->whereIn('id', $postIds)
->get();
任何有助于減少資料庫查詢或以 laravel 方式重構代碼的幫助將不勝感激。謝謝
uj5u.com熱心網友回復:
你給定的例子可以寫成:
$postWithRelatedPosts = Post::whereHas('category.post', function ($q) {
$q->where('id', 1);
})->get();
這是一個單一的查詢,但其中有 2 個子查詢。它會產生類似的東西:
select *
from `posts`
where exists (
select *
from `categories` inner join `category_post` on `categories`.`id` = `category_post`.`category_id`
where `posts`.`id` = `category_post`.`post_id` and exists (
select *
from `posts` inner join `category_post` on `posts`.`id` = `category_post`.`post_id`
where `categories`.`id` = `category_post`.`category_id` and `id` = ?
)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/334762.html
上一篇:PHP二叉樹遞回遍歷無限回圈問題
