如何将联接查询替换为whereHas?



我正在使用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('AppDictStatuses');
}

[更新]

我有一个错误:

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) 

在我的表中,我有表订单,其中是字段:dict_statuses_id和表dict_statuses字段:id,public_name

为什么错误是关于dict_statuses.orders_id

尝试 order::has('status'(->get((;

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

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

尝试定义本地键和外键。

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

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

请在迁移中包含该列

然后打电话

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

在控制器中

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

public function status(){
return $this->belongsTo('AppDictStatuses'):
}

最新更新