【问题标题】:Eloquent Laravel: whereHas is not selecting the model tableEloquent Laravel:whereHas 没有选择模型表
【发布时间】:2019-03-14 01:26:45
【问题描述】:

型号代码

 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%"`

【问题讨论】:

  • 可以迁移库存表吗
  • 你看到错误的是inventory table not inventories。也许尝试在模型中设置表名,如$table = 'yourTableName'

标签: sql laravel eloquent laravel-5.6


【解决方案1】:

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

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

您需要此查询顺利运行

【讨论】:

  • 先生,原始查询是由 laravel 雄辩的 whereHas 给出的。
【解决方案2】:

不要在 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    相关资源
    最近更新 更多