如何用wherehas替换联接查询?

时间:2018-09-26 12:50:40

标签: php eloquent laravel-5.6

我正在使用Laravel 5.6,并且有一个标准查询

    Order::where('dict_statuses_id', 1)
->leftJoin('dict_statuses', 'dict_statuses_id', '=', 'dict_statuses.id')
->get();

所以我有订单列表,其中在加入表后状态为1(新)的详细信息,我将状态视为“新建”或“完成”。有什么办法可以使用whereHas更改此查询?

我尝试使用

Order::whereHas('status', function($q){
            $q->where('dict_statuses_id', 1);
        })->get();

但是没有结果,在我的模型订单中

public function status()
    {
        return $this->hasMany('App\DictStatuses');
    }

[已更新]

我有一个错误:

  Column not found: 1054 Unknown column 'dict_statuses.orders_id' 
in 'where clause' (SQL: select * from `orders` where exists 
(select * from `dict_statuses` where `orders`.`id` = `dict_statuses`.`orders_id` and `dict_statuses_id` = 1) 
and `orders`.`deleted_at` is null) 

在我的表中,我有表 Orders (订单),其中字段为: dict_statuses_id 和表 dict_statuses ,其中的字段为: id public_name

为什么出错有关 dict_statuses.orders_id

3 个答案:

答案 0 :(得分:0)

您可以将变量传递给关系,以便有可能这样做。

public function status($id) {
    return $this->hasMany(DictStatuses::class)->where('dict_statuses_id', $id);
}

尝试定义本地键和外键。

$this->hasMany(DictStatuses::class, 'foreign_key', 'local_key');

答案 1 :(得分:0)

尝试Order :: has('status')-> get();

答案 2 :(得分:0)

我认为您的dict_statuses没有名为order_id的列。

请在您的迁移中包括该列

然后致电

Order::whereHas('status', function($q){
        $q->where('dict_statuses_id', 1);
    })->get();

在您的控制器中

或将订单模型中的关系更改为

public function status(){
 return $this->belongsTo('App\DictStatuses'):
}
相关问题