Laravel雄辩地得到所有记录,其中所有ID都存在多对多关系

时间:2016-04-13 09:17:07

标签: php laravel eloquent relationship

我有一个Posts表,它有三个字段idtitledescription

我的Post模型

class Post extends Model
{
    use SoftDeletes;

    protected $fillable = ['title', 'description'];

    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'post_tag');
    }
}

我的Tag模型

class Tag extends Model
{
    use SoftDeletes;

    protected $fillable = ['name'];

    public function posts()
    {
        return $this->belongsToMany(Post::class, 'post_tag');
    }
}

现在我想获得帖子&我有标签过滤器的paginate,例如我有两个标签animals&标识为news& 1的{​​{1}} 2。现在我想获取所有标记为1&的帖子2& paginate。这是我试过的

        Post:: with('tags')->whereHas('tags', function($q) {
            $q->whereIn('id', [1, 2]);
        })->paginate();

但是我在whereIn这里返回的帖子包含标签12both。但我想要帖子谁同时标记id 1& 2。

我正在使用Laravel 5.2

3 个答案:

答案 0 :(得分:2)

然后,您必须遍历您的ID列表以添加该条件。例如:

$query =  Post::with('tags');
foreach ($ids as $id) {
    $query->whereHas('tags', function($q) use ($id) {
        $q->where('id', $id);
    });
}
$query->paginate();

答案 1 :(得分:2)

我一直在寻找同样的事情并受到this stackoverflow MySQL answer的启发,我最终得到了这个

<强>代码:

Post:: with('tags')->whereHas('tags', function($q) {
    $idList = [1,2];
    $q->whereIn('id', $idList)
      ->havingRaw('COUNT(id) = ?', [count($idList)])
})->paginate();

因为我认为我可以在一些地方使用它,我已经把它变成了一个你可以view here的特征。如果您在Post类中包含该特征,则可以使用以下内容。

<强>代码:

Post::with('tags')->whereHasRelationIds('tags', [1,2])->paginate();

答案 2 :(得分:0)

我认为没有内置的方法,但我建议将foreach循环放在whereHas方法中,只是为了整洁。

$query = Post::with('tags')->wherehas('tags', function ($q) use ($ids) {
    foreach ($ids as $id) {
        $q->where('id', $id);
    }
})->paginate(10);
相关问题