查找评论具有多个标签多对多的幼虫关系

问题描述

嗨,我正在尝试使用多对多态,但以某种方式无法正常工作 我无法获得多对多多态关系的相关评论 我想按客户选择的标签进行评论

表结构:

review
> id - integer
> name - string

tags
> id - integer
> name - string

taggables
> tag_id - integer
> taggable_id - integer
> taggable_type - string

型号:

class Tag extends Eloquent
{
    public function reviews()
    {
        return $this->morphedByMany(Review::class,'taggable');
    }

}

class Review extends Eloquent
{
    public function tags()
    {
        return $this->morphToMany(Tag::class,'taggable');
    }
}

客户[tag_id_1,tag_id_2,tag_id_3,tag_id_4]的请求

类似[1、2、3、4、5]的请求 标签键数组

如果与此标签相关的评论找到并获得了评论,我尝试了类似的方法

与退货相关的评论代码

return Review::join('taggables','taggables.taggable_id','=','reviews.id')
        ->where('taggables.taggable_type',Review::class)
        ->whereIn('taggables.tag_id',[1,2,3,4,5])
        ->groupBy('reviews.id')
        ->orderBy('name','asc')
        ->get();

OR:

Review::WhereHas('tags',function ($query) {
        $query->whereIn('tags_id',5]);
    })->get();

我需要的结果: 唯一应该带有这些标签评论

review:{
name: "Review",tags :[1,5]
}

laravel eloquent relationships many-to-many-polymorphic

解决方法

您的查询中有错字。正确的taggables.tagable_id格式应为taggables.taggable_id。我不知道这是不是问题,但建议像下面这样编写代码。

在审阅模型中定义如下关系:

public function tags()
{
    return $this->morphToMany(Tag::class,'taggable','taggables','taggable_id','tag_id');
}

并在Tag模型中定义如下关系:

public function reviews()
{
    return $this->morphedByMany(Review::class,'tag_id','taggable_id');
}

,当您要返回特定标签的评论时,请执行以下操作:

$tag=Tag::find(1);
$tagReviews=$tag->reviews;
,

如果您想要包含所有标签的评论,这是一种方法:

$tagIds = [1,2,3,4,5];
$reviews = Review::query();
foreach($tagIds as $id){
 $reviews->whereHas('tags',function($query) use ($id) {
   return $query->where('id',$id);
 });
}
$reviewsWithAllThoseIds = $reviews->get(); 

//if you don't want to use foreach.
collect($tagIds)->each(function($id) use ($reviews){
    $reviews->whereHas('tags',function($q) use ($id) {
        return $q->where('id',$id);
    });
});

这应该为您提供包含数组中所有ID的所有标签的评论。