搜索具有多对多变形关系的模型

时间:2015-12-04 10:45:11

标签: php laravel laravel-5 eloquent relationships

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'))

我在寻找类似的例子时感到难过,过度疲惫,无处可去。我错过了什么?我想要达到的目的是什么是正确的术语,所以我可以将它添加到我的词汇表中以供将来使用?

1 个答案:

答案 0 :(得分:1)

我认为这只需要是您尝试过滤的每个标记的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子句