假设我有一个Group
和Student
模型,这是一对多关系;
Group
具有许多Student
,每个Student
具有id
和tuition
属性。
所以我想让Group包含学生人数和所有学费。
这是我的代码:
Group::with(['student'=>function($query){
$query->select(DB::raw('count(`id`) as numbers, sum(tuition) as total'));
}])->paginate(10);
它不起作用,我尝试打印sql和sql:
select count(id) as numbers, sum(tuition) as total from `group` where `student`.`group_id` in (`1`, `2`, `4`, `5`, `6`, `7`, `8`, `11`, `12`, `13`, `14`)
在mysql中运行原始sql时,我可以得到结果,但是laravel不返回有关count
或sum
的任何信息。
答案 0 :(得分:0)
使用withCount()
代替with()
:
Group::withCount([
'student as numbers',
'student as total' => function($query) {
$query->select(DB::raw('sum(tuition)'));
}
])->paginate(10);
Laravel 5.2解决方案:
Group::selectRaw('(select count(*) from students where groups.id = students.group_id) as numbers')
->selectRaw('(select sum(tuition) from students where groups.id = students.group_id) as total')
->paginate(10);
答案 1 :(得分:0)
您可以使用withCount()
代替with()
https://laravel.com/docs/5.5/eloquent-relationships#counting-related-models
答案 2 :(得分:0)
测试了很多;
当我使用find
时,仅获得一行。
Group::with(['student'=>function($query){
$query->select(DB::raw(' group_id ,count(`id`) as number, sum(tuition) as total'));
}])->find(1);
有效。
我唯一想念的是我需要选择student.group_id
,这意味着foreign key
与hasMany
的关系。
但是当您想使用paginate
或get
方法来获取多行时。
您只会在第一个模型对象中获得总计结果,而其他对象则为空。
{
"id": 1,
"name":"first",
"student": [
{
"group_id": 1,
"number": 129,
"total": "38700.00"
}
]
},
{
"id": 2,
"name":"second",
"student": []
},
{
"id": 3,
"name":"third",
"student": []
},
只需添加->groupBy('group_id)
,您就会得到想要的内容
Group::with(['student'=>function($query){
$query->select(DB::raw('id, class_id ,count(`id`) as numbers, sum(tuition) as total'))->groupBy('group_id');
}])->paginate(10);
结果:
{
"id": 1,
"name":"first",
"student": [
{
"group_id": 1,
"number": 40,
"total": "12000.00"
}
]
},
{
"id": 2,
"name":"second",
"student": [
{
"group_id": 2,
"number": 43,
"total": "12900.00"
}
]
},
{
"id": 3,
"name":"third",
"student": [
{
"group_id": 3,
"number": 46,
"total": "13800.00"
}
]
},