laravel - Laravel - 我如何获取按状态分组的客户订单
问题描述
我有一个无法解决的情况,我有 3 个表/模型,其结构如下:
- 客户型号:
Client->hasMany(Order::Class)
- 订购型号:
Order->belongsTo(Client::Class)
和Order->belongsTo(Status::Class)
- 状态模型:
Status->hasMany(Order::class)
我希望能够让每个客户的订单按他们的状态分组,例如:3 取消 - 4 完成 - 5 处理
我试过这个但没有用:(
Client Model {
public function {
return $this->orders()->selectRaw('status_id, count(id) as total')->groupBy('status_id);
// orders() = is the relation a client hasmany orders
}
}
谁能帮忙谢谢
解决方案
以这种方式定义您在客户端模型中的关系
public function orders()
{
return $this->hasMany(Order::class);
}
public function getOrdersCompletedAttribute()
{
return $this->orders->where('id_status', 5)->count();
}
public function getOrdersProcessingAttribute()
{
return $this->orders->where('id_status', 1)->count();
}
假设状态 1 = '处理' 和 5 = '完成'
您可以像这样访问 de 属性:
$client->orders_completed
获得 4