雄辩的Laravel:哪里没有选择模型表

时间:2018-10-09 09:52:39

标签: sql laravel eloquent laravel-5.6

型号代码

 public function product(){
        return $this->belongsTo('App\Models\Ecommerce\Product');
 }

控制器代码

$inv = Inventory::where('is_deleted', 0)->with(['product', 'size','color'])->orderByDesc('id'); 



if($request->inv_filter == 'code'){
    $inv = $inv->whereHas('product', function ($q) use ($request){
    $q->where('code', 'like', "%".$request->searchText."%")->get();
 });
 dd($inv);
  

错误:inventories.product_id不存在。但是它确实存在。当我使用$ inv-> toSql()时。它提供的原始sql查询是错误的。该如何解决?

SELECT * FROM `products` WHERE `inventories`.`product_id` = `products`.`id` AND `code` like `"%jean67%"`

2 个答案:

答案 0 :(得分:0)

您的原始查询存在查询缺少JOIN语句的问题。

 SELECT * FROM products JOIN inventories WHERE products.id = 
 inventories.product_id ;

此查询可以顺利进行,您需要

答案 1 :(得分:0)

请勿在{{1​​}}闭包中调用get。请尝试以下操作:

whereHas
相关问题