問題描述
我有一個 Posts
表,它有三個字段 id
、title
、description
.
I have a Posts
table it has three fields id
, title
, description
.
我的發布
模型
class Post extends Model
{
use SoftDeletes;
protected $fillable = ['title', 'description'];
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tag');
}
}
我的標簽
模型
class Tag extends Model
{
use SoftDeletes;
protected $fillable = ['name'];
public function posts()
{
return $this->belongsToMany(Post::class, 'post_tag');
}
}
現在我想獲得帖子&在我有標簽過濾器的地方分頁,例如我有兩個標簽 animals
&news
id 1
&2
.現在我想獲取所有帶有標簽 1
& 的帖子2
&分頁
.這是我試過的
Now I want to get posts & paginate where I have a tag filter e.g I have two tags animals
& news
which has id 1
& 2
. Now I want to get all posts which has tag 1
& 2
& paginate
. Here is what I tried
Post:: with('tags')->whereHas('tags', function($q) {
$q->whereIn('id', [1, 2]);
})->paginate();
但在這里,我是 whereIn
,它返回的帖子有標簽 1
或 2
或 both
.但我想要同時具有標簽 ID 1 和標簽的帖子2.
But here as I am whereIn
it returns posts has tags 1
or 2
or both
. But I want post who has both tag id 1 & 2.
我使用的是 Laravel 5.2
.
推薦答案
我一直在尋找相同的東西并受到 this stackoverflow MySQL answer,我已經結束了這個
I have been looking for the same thing and inspired by this stackoverflow MySQL answer, I have ended up with this
代碼:
Post:: with('tags')->whereHas('tags', function($q) {
$idList = [1,2];
$q->whereIn('id', $idList)
->havingRaw('COUNT(id) = ?', [count($idList)])
})->paginate();
因為我想我可能會在一些地方使用它,所以我已經把它變成了一個特性,你可以在這里查看.如果您在 Post 類中包含 trait,您可以像下面這樣使用.
Because I think I might use it in a few places I have made it into a trait which you can view here. Which if you included the trait in your Post class you could use like the following.
代碼:
Post::with('tags')->whereHasRelationIds('tags', [1,2])->paginate();
這篇關于Laravel eloquent 獲取所有記錄,其中包含多對多關系中的所有 id的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!