Eloquent Laravel: whereHas 没有选择模型 table

Eloquent Laravel: whereHas is not selecting the model table

型号代码

 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);

Error: inventories.product_id doesn't exist. But it actually exists. When i used $inv->toSql(). The raw sql query it gives is wrong. How to fix this?

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

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

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

此查询工作顺利你需要

不要在 whereHas 闭包中调用 get。请尝试以下操作:

Inventory::with(['product', 'size', 'color'])->when($request->inv_filter === 'code', function ($builder) {
    $builder->whereHas('product', function ($q) {
        $q->where('code', 'like', "%".request()->searchText."%");
    });
})->where('is_deleted', 0)->orderByDesc('id')->get();