仅当hasMany关系具有元素时才获取对象列表

时间:2021-04-11 10:09:00

I have 3 tables

我有3张桌子

Shops    - id, place_id, name...
Products - id, shop_id, name ...
Product_Tag - product_id, tag_id ... (pivot table)
Tags - id....

And I would like to get results in array like this:

我希望得到如下数组的结果:

array [
  0 => [
    "id" => 1,
    "name" => "Shop name",
    "products" => [...]
  ]
]

but I would like to search it by place_id and tag name. Something like this:

但我想通过place_id和标签名称进行搜索。像这样的东西:

$shops = Shop::where('place_id', 1)
     ->with(array('products' => function($query)
     {
        $query->whereHas('tags', function ($query) {
            $query->where('slug', 'tagname1');
        });
     }))->get();

This is working okay. But if none of shop products has that tag, I would still get Shop object with empty products array. Everything is okay if in that shop, at least one product has that tag. I don't want to get shop if it has empty products list. Also I think it's overhead to foreach that array and search for empty arrays and then to remove shop object. Is there better way to don't fetch from database at all ?

这工作正常。但如果没有商店产品有这个标签,我仍然会得到带有空产品阵列的Shop对象。如果在那个商店,至少有一个产品有这个标签,一切都还可以。如果它有空产品清单,我不想去购物。另外我认为这是开头那个数组并搜索空数组然后删除商店对象的开销。是否有更好的方法不从数据库中取出?

1 个解决方案

#1


You can nest your 'has' statements. See: http://laravel.com/docs/5.0/eloquent#querying-relations

您可以嵌套'has'语句。请参阅:http://laravel.com/docs/5.0/eloquent#querying-relations

So this should work:

所以这应该工作:

$shops = Shop::where('place_id', 1)->whereHas('products.tags', function ($query) {
    $query->where('slug', 'tagname1');
 })->with(products.tags)->get();

#1


You can nest your 'has' statements. See: http://laravel.com/docs/5.0/eloquent#querying-relations

您可以嵌套'has'语句。请参阅:http://laravel.com/docs/5.0/eloquent#querying-relations

So this should work:

所以这应该工作:

$shops = Shop::where('place_id', 1)->whereHas('products.tags', function ($query) {
    $query->where('slug', 'tagname1');
 })->with(products.tags)->get();