Laravel雄辩获得所有记录,其中所有ids在许多关系中 [英] Laravel eloquent get all records wherehas all ids in many to many relation
问题描述
我有一个帖子
表格,它有三个字段 id
, title
,描述
。
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');
}
}
现在我想要发帖分页,我有一个标签过滤器,例如我有两个标签动物
& 新闻
其中有 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
或都
。但是我想要帖子谁拥有标签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
。
推荐答案
然后,您必须循环通过您的ID列表来添加该条件。例如:
You'll have to loop through your list of ids to add that condition, then. For instance:
$query = Post::with('tags');
foreach ($ids as $id) {
$query->whereHas('tags', function($q) use ($id) {
$q->where('id', $id);
});
}
$query->paginate();
这篇关于Laravel雄辩获得所有记录,其中所有ids在许多关系中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!