如何获取数据库字段值的总和与laravel

时间:2015-08-11 11:45:54

标签: laravel-4

我表 student_atendence 表字段是(id,studid,attendence)。

这是我的表 student_atendence

id   studid   attendence      
1    28            1     
2    31            0  
4    32            1   
5    28            0 
6    31            1   
7    32            1   
9    28            1   
10   31            1   
11   32            1   
13   28            1   
14   31            0   
15   32            1   
17   28            0   
18   31            1   
19   32            1   
21   28            1   
22   31            1   
23   32            0   
24   28            1   
25   31            1   
26   32            0  

我想要这样的结果

id studid total 1' s 0' s

1    28        6          1

2    31        6          1

3    32        5          2

如何分别获得每个学生的总注意数= 1和注意力= 0。

例如:28 - 6(总共1秒)和1(总计0秒),31 - 6(总共1秒)和1(总计0秒),32 - 5(总共1秒)和2(总计0秒)。

mycontroller代码foreach($students as $student){ $cunt1 = DB::table($wys_attendence_table) ->where('studid',$student->id) ->where('amonth',$amonth) ->where('ayear',$ayear) ->where('attendence','=',1) ->count(); $cunt0 = DB::table($wys_attendence_table) ->where('studid',$student->id) ->where('amonth',$amonth) ->where('ayear',$ayear) ->where('attendence','=',0) ->count(); //var_dump($cunt1); //var_dump($cunt0); }

我的观看页面@foreach($stud_attend as $stud_attends) @if($student->id == $stud_attends->studid)
@if($stud_attends->attendence == 1) <td><font color="green" size="3">p</font></td> @elseif($stud_attends->attendence == 0) <td><font color="red" size="3">a</font></td> @endif <td>{{$cunt1}}</td> @endif @endforeach

我从var_dump($ cunt0),var_dump($ cunt1)得到了正确的答案,但在视图页面中无效。

如何更改我的代码??

1 个答案:

答案 0 :(得分:0)

试试这个......

DB::table($wys_attendence_table)
->select(DB::raw('studid, sum(attendence = 1) AS `total1`, sum(attendence = 0) AS `total0`'))
->where('studid',$student->id)
->where('amonth',$amonth)
->where('ayear',$ayear);
相关问题