Laravel eloquent get all records wherehas all ids in many to many relation(Laravel eloquent 获取所有记录,其中包含多对多关系中的所有 id)
问题描述
我有一个 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel eloquent 获取所有记录,其中包含多对多关系中的所有 id
基础教程推荐
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01