Laravel 具有count和groupby雄辩的查询
我想在视图中有一个表,显示与会议相关的所有注册类型、每种注册类型的价格和售出的注册数量 例如,如果id为1的会议有两种具有以下列和值的注册类型: rtype1名称,0.00美元价格,20个容量 rtype2名称,5.00美元价格,10个容量 在rtype1中注册了20名参与者,在RType2中注册了5名参与者。我想显示一个如下表:Laravel 具有count和groupby雄辩的查询,laravel,eloquent,Laravel,Eloquent,我想在视图中有一个表,显示与会议相关的所有注册类型、每种注册类型的价格和售出的注册数量 例如,如果id为1的会议有两种具有以下列和值的注册类型: rtype1名称,0.00美元价格,20个容量 rtype2名称,5.00美元价格,10个容量 在rtype1中注册了20名参与者,在RType2中注册了5名参与者。我想显示一个如下表: Registration Type name Price Sold/capacity rtype1
Registration Type name Price Sold/capacity
rtype1 0.00$ 20/20
rtype2 5.00$ 5/10
我不知道如何正确地实现这一点。现在,我有这个查询来获取每个注册类型和每个注册类型的计数:
$participantsOfEachType = Participant::
select(DB::raw('registration_type_id, count(registration_type_id)'))
->groupBy('registration_type_id')->get();
此查询返回以下结果。但他没有考虑召开一次具体的会议。你知道什么是必要的考虑一个特定的会议ID,所以有可能在表中显示结果,就像上面表中的例子?
Collection {#271 ▼
#items: array:2 [▼
0 => Participant {#282 ▼
...
#attributes: array:2 [▼
"registration_type_id" => 1
"count(registration_type_id)" => 2
]
...
}
1 => Participant {#279 ▼
...
#attributes: array:2 [▼
"registration_type_id" => 2
"count(registration_type_id)" => 2
]
...
}
]
}
问题的相关模型:
用户模型:
public function registrations(){
return $this->hasMany('App\Registration','user_that_did_registration');
}
注册模式:
// user that did the registration
public function customer(){
return $this->belongsTo(User::class, 'user_that_did_registration', 'id');
}
public function participants(){
return $this->hasMany('App\Participant');
}
public function conference(){
return $this->belongsTo('App\Conference');
}
会议模式:
public function registrations(){
return $this->hasMany('App\Registration', 'conference_id');
}
参与者模式:
public function registration(){
return $this->belongsTo('App\Registration');
}
public function registration_type(){
return $this->belongsTo('App\RegistrationType');
}
试一试
选择会议id,
组_concat_ws':',注册类型id,cnt
从中选择会议id、注册类型id、计数*为cnt
从t
按会议id、注册类型id分组
商标
按会议编号分组
按会议编号排序 我假设您的注册类型模型具有以下映射
Class RegistrationType Extends Model{
public function participants(){
$this->hasMany('App\Participants','registration_type_id')
}
}
然后,对于预期的输出,您可以获得如下数据:
$conference_id = 1;
$registrationTypes = RegistrationType::withCount('participants')
->whereHas('participants.registration.conference',function($query) use ($conference_id){
$query->where('id','=', $conference_id)
});
->get();
当您在结果中循环时,$registrationTypes中的每一行都将有一个属性participants\u count,它将为您提供该注册类型的参与者计数
谢谢,这个问题很有说服力,但是通过这个查询,它显示了一个表不存在错误。您只需要用表名替换即可。您可以包括您的模型以及它们之间定义的关系,或者为您的表提供表定义和示例数据集谢谢,我用模型更新了这个问题。