【问题标题】:whereHas not working as expectedwhere 没有按预期工作
【发布时间】:2014-10-16 15:34:13
【问题描述】:

我正在尝试获取具有$item_ids = array('1', '17'); 之一的所有Shops。

但是,下面的代码并没有像我预期的那样做——它只是把所有的商店都交给了我。

$shops = Shop::whereHas('items', function($query) use ($item_ids) {

                    $query->where('items.id', '=', $item_ids[0]);

                    foreach(array_slice($item_ids, 1) as $item_id) {
                        $query->orWhere('items.id', '=', $item_id);
                    }
                })
                ->get(array('shops.id', 'shops.shop_name', 'shops.lat', 'shops.lng'));

我只得到带有指定Items 之一的Shops?

【问题讨论】:

    标签: php mysql laravel orm


    【解决方案1】:

    你应该使用:

    $shops = Shop::whereHas('items', function($query) use ($item_ids) {    
         $query->whereIn('id', $items_ids);
    })->get();
    

    $shops = Shop::whereHas('items', function($query) use ($item_ids) {    
         $query->whereIn('id', $items_ids);
    })->select('shops.id', 'shops.shop_name', 'shops.lat', 'shops.lng')->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2020-03-18
      • 2012-06-14
      • 2014-11-15
      • 1970-01-01
      • 2012-07-02
      • 2011-09-07
      相关资源
      最近更新 更多