搜索具有多对多多态关系的模型

Searching Model with Many to Many Polymorphic Relation

tags example in the Laravel docs 之后,我已经成功地实现了图像标记,现在我正在尝试通过所述标记进行搜索。

从单个标签中提取图像效果很好,但我在尝试搜索包含多个标签的图像时遇到了障碍。

这是我得到的最接近的结果,它按预期工作,但不是我想要的。

/**
* $tag string, example: 'baseball'
* $tags array, example: ['baseball','stadium','new.york.yankees']
*/
Image::whereHas('tags', function($query) use ($tag,$tags) {
    if (count($tags)) {
        // Retrieves images tagged as 'baseball' OR 'stadium' OR 'new.york.yankees'
        // Instead, I want it to retrieve images that have all three tags
        $query->whereIn('tag', $tags);

        // The following returns no results, though there are images tagged correctly.
        // I presume this is an incorrect approach.
        foreach ($tags as $tag) {
            $query->where('tag', '=', $tag);
        }
    } else {
        // Retrieves images tagged as 'baseball'
        $query->where('tag', '=', $tag);
    }
})->orderBy('created_at', 'desc')
->paginate(config('app.images_per_page'))

在搜索类似示例时,我感到难过、疲惫不堪,而且一无所获。我错过了什么?我想要实现的目标的正确术语是什么,以便我可以将其添加到我的词汇表中以备将来使用?

我认为这只需要是您尝试过滤的每个标签的 whereHas 语句。这将在查询中创建一个 AND 语句。

if(!$count($tags)) $tags = [$tag]; //for simplicity lets always have an array

$imageQuery = Image::query();
foreach($tags as $tag){
    $imageQuery = $imageQuery->whereHas('tags', function($query) use ($tag) {
        $query->where('tag', '=', $tag);
    });
}
$results = $imageQuery->orderBy('created_at', 'desc')
    ->paginate(config('app.images_per_page'))->get();

代码未经测试,但从逻辑上讲,我认为每个标签都需要一个 where 子句