查询多对多关系laravel

时间:2015-09-29 22:00:31

标签: mysql laravel eloquent

我试图用Laravel 5 eloquent查询多对多的关系,使用数据透视表,我m trying to retrieve only "articles" that has tag "A" and tag "B" together, but not succeed, eloquent带来带有标签的文章" A"并标记" B",有什么办法可以做到这一点?没有任何风格可行。

$tags = [1,2,3];  
$result = Timetable::with([
    'tags' => function($query) use($tags){
        foreach($tags as $tag) {
            $query->where('id', $tag);
        }
    }
])->paginate();

$result = Timetable::with(['tags'])
                    ->whereHas('tags' => function($query) use($tags){
                            $query->whereIn('tag_id',$tags);
                    }
                )->paginate();

1 个答案:

答案 0 :(得分:2)

假设您遵循了Laravel关于您的关系和外键的命名规则:

获取包含任何标记的时间表

$result = Timetable::with('tags')->whereHas('tags', function($query) use ($tags) {
    $query->whereIn('tag_id', $tags);
})->paginate();

获取具有所有标签的时间表(不接受其他标签)

$result = Timetable::with('tags')->whereHas('tags', function($query) use ($tags) {
    $query->whereIn('tag_id', $tags);
}, '=', count($tags))->paginate();

获取包含所有标记的时间表,但它们也可能包含其他标记

$result = Timetable::with('tags')->whereHas('tags', function($query) use ($tags) {
    $query->whereIn('tag_id', $tags);
}, '>=', count($tags))->paginate();

与上述相同,但从结果中排除不匹配的标签

$result = Timetable::with(['tags' => function($query) use ($tags) {
    $query->whereIn('tag_id', $tags);
}])->whereHas('tags', function($query) use ($tags) {
    $query->whereIn('tag_id', $tags);
}, '>=', count($tags))->paginate();
相关问题