【问题标题】:Get list of objects only when hasMany relations has element仅当 hasMany 关系具有元素时才获取对象列表
【发布时间】:2015-07-20 11:50:30
【问题描述】:

我有 3 张桌子

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

我想得到这样的数组结果:

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

但我想通过 place_id 和标签名称搜索它。像这样的:

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

这工作正常。但是,如果所有商店产品都没有该标签,我仍然会得到带有空产品数组的 Shop 对象。如果在那家商店中,至少有一种产品具有该标签,则一切正常。如果它有空的产品列表,我不想去商店。此外,我认为 foreach 该数组并搜索空数组然后删除 shop 对象是开销。有没有更好的方法根本不从数据库中获取?

【问题讨论】:

    标签: php arrays laravel eloquent laravel-5


    【解决方案1】:

    你可以嵌套你的'has'语句。见:http://laravel.com/docs/5.0/eloquent#querying-relations

    所以这应该有效:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 2023-03-15
      • 2022-01-24
      • 1970-01-01
      • 2012-10-21
      • 2016-01-01
      相关资源
      最近更新 更多