我试图用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();
答案 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();