【问题标题】:Laravel eloquent "with" and "where" with multiple tablesLaravel 雄辩的“with”和“where”与多个表
【发布时间】:2018-09-18 13:57:34
【问题描述】:

我的项目中有 3 张桌子:

  1. 商场
  2. 商店
  3. 产品

我有一个页面可以在整个数据库中搜索产品。我需要一个选项,他们可以通过商场名称搜索产品。所以我这样构建了我的代码:

$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'

我的查询有问题吗?谢谢

【问题讨论】:

  • shop.mall 是什么意思?
  • 您还应该发布所有 3 个表的模型,以便我们可以看到您的关系。

标签: php mysql laravel eloquent


【解决方案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"] . '%');
        });
    }

【讨论】:

猜你喜欢
  • 2017-11-05
  • 2018-12-09
  • 1970-01-01
  • 2021-02-13
  • 2019-01-28
  • 2017-01-30
  • 2014-10-11
  • 2018-05-19
  • 2019-03-14
相关资源
最近更新 更多