Laravel雄辩,#34;与#34;和"其中"有多个表

时间:2018-04-09 08:17:21

标签: php mysql laravel eloquent

我的项目中有3个表格:

  1. 购物中心
  2. 商店
  3. 产品
  4. 我有一个页面来搜索整个数据库中的产品。我需要一个选项,他们可以通过商城名称搜索产品。所以我构建了这样的代码:

    $query = Product::with('shop', 'shop.mall');
    
    if (!empty($data["keyword"])) {
        $query = $query->where(function($q) use($data) {
             $q->where('shop.mall.name', 'LIKE', '%' . $data["keyword"] . '%')->orWhere('shop.mall.keyword', 'LIKE', '%' . $data["keyword"] . '%');
        });
    }
    

    但是它显示了这个错误:

    Column not found: 1054 Unknown column 'shop.mall.name' in 'where clause'
    

    我的查询有问题吗?谢谢

1 个答案:

答案 0 :(得分:1)

要在关系中搜索whereHas(),它会创建子查询并返回在shop.mall中过滤的数据。

    $query = Product::with('shop', 'shop.mall');

    if (!empty($data["keyword"])) {
        $query = $query->whereHas('shop.mall',function($q) uses ($data){
            $q->where('name', 'LIKE', '%' . $data["keyword"] . '%')->
              orWhere('keyword', 'LIKE', '%' . $data["keyword"] . '%');
        });
    }