我的项目中有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'
我的查询有问题吗?谢谢
答案 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"] . '%');
});
}