laravel - 计算注册类型价格 > 0 的会议中的注册
问题描述
我有一个查询来计算会议中的注册数量:
$registrationsCount = $conference->registrations->count();
但我只想获得与价格> 0 的注册类型相关的会议注册。你知道如何实现吗?例如,如果会议“测试会议”有两种注册类型“rt1 和 rt2”,rt1 的价格为 0,rt2 的价格为 10,并且注册类型“rt2”中有 5 个注册,则查询应返回 5 ,因为会议有5个付费注册。
会议模式:
public function registrationTypes(){
return $this->hasMany('App\RegistrationType', 'conference_id');
}
public function registrations(){
return $this->hasMany('App\Registration', 'conference_id');
}
注册型号:
public function registration_types(){
return $this->belongsToMany('App\RegistrationType', 'registration_registration_types');
}
public function conference(){
return $this->belongsTo('App\Conference');
}
注册类型型号:
public function conference(){
return $this->belongsTo('App\Conference');
}
public function registrations(){
return $this->belongsToMany('App\Registration', 'registration_registration_types');
}
参与者型号:
public function registration(){
return $this->belongsTo('App\Registration');
}
public function registration_type(){
return $this->belongsTo('App\RegistrationType');
}
表结构:
conferences: id, name
registrations: id, status, conference_id, user_that_did_registration
registration_types: id, name, price, conference_id
participants: id, registration_id, registration_type_id, name
解决方案
老实说,我并没有完全理解你的要求,但我看到了以下两种可能性:
Conference::whereHas('registrationTypes', function ($query) {
$query->where('price', '>', 0);
})
->withCount('registrations')
->get();
// will give you something like this
[
{
"id": 1,
"name": "Laracon",
"registrations_count": 100
}
]
或者,您可以在计数中执行价格检查
Conference::withCount(['registrations' => function ($query) {
$query->whereHas('registration_types', function ($query) {
$query->where('price', '>', 0);
});
}])
->get();
推荐阅读
- android - React-Native:如何在 Android 中访问 react-native 应用程序的权限?
- arrays - VBA Excel:如何通过函数将值分配给数组中的空槽
- android - 可关闭小部件的边框拖动端
- java - 用嵌入式数据库替换真实数据源进行测试
- cors - 当我尝试使用 Fetch from React 进行 POST 时,Cors 阻止了错误 403
- elixir - 使用 Phoenix 应用程序监控文件系统(文件创建)
- vue.js - 无法使用动态 Vuex 存储数据填充 VueJS 日历插件的数据数组
- mysql - 存储过程在 localhost 中有效,但在服务器中无效
- swift - 尝试在 SwiftUI 中的 UIViewRepresentable 中将 HTML 转换为 AttributedString
- php - 无法为命名路由“参与者”生成 URL,因为此类路由不存在