简体   繁体   中英

Searching Model with Many to Many Polymorphic Relation

Following the tags example in the Laravel docs , I've successfully implemented image tagging, and now I'm trying to search by said tags.

Pulling an image from a single tag works well, but I'm hitting a roadblock when trying to search for images containing multiple tags.

This is the closest I've gotten, and it works as expected but it is not what I desire.

/**
* $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'))

I'm stumped, overtired, and getting nowhere while searching for similar examples. What am I missing? What is the correct terminology for what I am trying to achieve, so I can add it to my vocabulary for future endeavors?

I think this just needs to be a whereHas statement for each of the tags you are trying to filter by. This would create an AND statement within the query.

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();

Code is not tested but logically I think you need a where clause for each tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM