jeudi 6 juin 2019

Proper way of finding Articles that share a Tag in many-to-many relation on Laravel's Eloquent

I have three tables, an articles table, a tags table, and an intermediate pivot table called article_tags, which only contains an article_id and tag_id, forming a many-to-many-relationship.

I want to write a function that receives an Article, and returns a collection or query with all Articles that share at least one tag with the received Article, after trying a bunch of different solutions, I have this:

public function scopeRelated($query, Article $article)
{
    return $query->whereHas('tags', function ($query) use ($article) {
        // I've tried a bunch of different lines, like just $article->tags
        $query->whereIn('tags', $article->tags->pluck('id'));
    });
}

This returns an error:
Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tags' in 'where clause' (SQL: select * from articles where exists (select * from tags inner join article_tag on tags.id = article_tag.tag_id where articles.id = article_tag.article_id and tags in (1, 6, 4)))'

Evidently, Eloquent is trying to match the tags to a 'tags' column on the Articles table, which doesn't exist. What would be the correct way of asking for what I want?



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2MMtB1N
via IFTTT

Aucun commentaire:

Enregistrer un commentaire