【问题标题】:Laravel Eloquent find posts that has all the given tagsLaravel Eloquent 查找具有所有给定标签的帖子
【发布时间】:2023-04-06 22:35:01
【问题描述】:

考虑如下 3 个表格

class Post extends Model
{
    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'post_tags', 'post_id', 'tag_id');
    }

}

posts

|id | title   |
+---+---------+
|1  |  post1  |
|2  |  post2  |
|3  |  post3  |
|4  |  post4  |

tags

|id |  value  |
+---+---------+
|1  |  tag01  |
|2  |  tag02  |
|3  |  tag03  |
|4  |  tag04  |

post_tags

|  post_id | tag_id  |
+----------+---------+
|     1    |    1    |
|     2    |    3    |
|     2    |    4    |
|     3    |    1    |
|     4    |    1    |
|     4    |    4    |

唯一同时包含tag01tag04 的帖子是id = 4 的帖子

但是当我用这个代码得到posts

Post::whereHas('tags', function($q) {
  $q->whereIn('tag_id', [1, 4]);
}

我收到了所有带有tag01tag04 的帖子。

我想得到Posts,其中tag01tag02 在其tags 关系中。

如何使用Eloquent 或如果使用QueryBuilder 无法实现此结果

【问题讨论】:

    标签: php laravel eloquent has-and-belongs-to-many


    【解决方案1】:

    我认为你可以使用多个 where 条件

     Post::whereHas('tags', function($q) {
           $q->where('tag_id', 1);
       
        })->whereHas('tags', function($q) {
           $q->where('tag_id', 4);
       
        })->get();
    

    如果 id 是动态的,那么

    $id=[1,4];
        Post::where(function($query)use($id){
            foreach ($id as $value){
                $query->whereHas('tags',function ($query)use($value){
    
                    $query->where('tag_id',$value);
    
    
                });
            }
    
    
        })->get();
    

    【讨论】:

    • 更新后的答案按预期工作,谢谢。
    • @HadiSharghi .lagbox 答案也很有效,而且很简单
    【解决方案2】:

    whereHas 方法接受更多参数,其中一个是计数:

    Post::whereHas('tags', fn ($q) => $q->whereIn('tag_id', $tags), '=', count($tags))->get();
    

    如果您正在寻找[1, 4],这就是说找到我所有带有标签14 的帖子,然后只选择那些恰好有2 个(计数)的帖子,这意味着找到所有具有所有这些标签的帖子。

    Laravel 8.x Docs - Eloquent - Relationships - Querying Relationship ExistencewhereHas

    【讨论】:

    • 简单干净。
    • @HadiSharghi 我为你添加了更多描述
    • 非常聪明!感谢您的澄清
    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    相关资源
    最近更新 更多