laravel获取所有具有关系数组的模型
问题描述:
I have a Product model with Tags relation:
class Product
{
public function tags()
{
return $this->belongsToMany('tags')
and
class Tags
{
public function products()
{
return $this->belongsToMany('products')
how can i retrieve products
that have all of tags
with id of [1,2,3]
答
Use whereHas()
with all four parameters:
$tagIds = [1, 2, 3];
$products = Product::whereHas('tags', function($query) use($tagIds) {
$query->whereIn('tags.id', $tagIds);
}, '=', count($tagIds))->get();