WhereIn 和关系

pan*_*hro 5 php laravel eloquent

我有3张桌子:

  • 文章
  • 标签
  • article_tag

它们都是具有枢轴的多对多关系。

我需要查询它以获取所有具有标签数组的文章:

Article::with('tags')->whereIn('id', $tagIdArray)->get();
Run Code Online (Sandbox Code Playgroud)

上面的问题在于它返回了 ID 为 $tagIdArray 的文章。如何约束结果以便我在标签关系上使用 whereIn?

Wad*_*der 7

你的想法是对的,但有点离题。使用这些with('tags')函数只是将文章与相关标签一起拉出来,在with()函数之后链接的查询仍然适用于文章模型。

要查询关系,您可以执行以下操作

$tagIdArray = [1, 3, 5, 7, 9];

$articles = Article::whereHas('tags', function($query) use ($tagIdArray) {
    /**
      * Now querying the Tags relation. So anything in this closure will query the Tags
      * relation, but outside of the closure, you're back to querying the Articles.
      */
    $query->whereIn('id', $tagIdArray);
})->get();
Run Code Online (Sandbox Code Playgroud)

这是关于查询关系的 Laravel 文档http://laravel.com/docs/4.2/eloquent#querying-relations