我是编程新手。我有桌子
check_1,check_2,check_3 ..etc
------------------------------
1 1 1
0 0 1
1 0 1我想要这个输出:
column_name, count_true
-----------------------
check_1 2
check_2 1
check_3 3我已经使用联合函数在mysql中尝试了它,但是当我尝试在laravel中应用它时,我在联合方面遇到了问题。有没有一个无联盟的查询可以产生这样的输出?
提前感谢
发布于 2019-03-10 21:50:51
你可以这样做。db中的一个查询
$records = DB::table('your_table')->get();
$check1Count = $records->where('check_1', 1)->count();
$check2Count = $records->where('check_2', 1)->count();
$check3Count = $records->where('check_3', 1)->count();
......或
$records = DB::table('your_table')->get();
$columns = ['check_1', 'check_2', 'check_3', ...];
$data = [];
foreach($columns as $column) {
$data[] = [
'column_name' => $column,
'count_true' => $records->where($column, 1)->count();
];
}你也可以这样做,但是它有很多查询
$check1Count = DB::table('your_table')
->selectRaw('COUNT(check_1) as count')
->where('check_1', 1)
->first()
->count;
$check2Count = DB::table('your_table')
->selectRaw('COUNT(check_2) as count')
->where('check_2', 1)
->first()
->count;
.....发布于 2019-03-10 21:58:39
规范化的方法可能如下所示:
response_id checkbox
1 1
1 2
1 3
2 3
3 1
3 3发布于 2019-03-10 22:23:01
您不需要联合,只需查询所有数据并在Laravel上处理即可。假设你使用eloquent to $data变量查询所有数据,那么你应该这样做:
//preparing a variable to hold all 24 database field value
$total = [];
foreach ($data as $d) {
//do this for all 24 database field
if ($d->check_1) {
$total[1]++;
}
if ($d->check_2) {
$total[2]++;
}
...
}通过使用这种方式,您不能检查$totalindex变量的结果。是的,有一种更好的存储数据的方法,而不是为每个用户保存所有字段。您可以将所有选中的值存储在数据库中,如下所示:
user_id checkbox_id
1 3
1 5
1 9
1 24
2 23
3 2
3 3它更有效,因为您不需要保存未选中的复选框值,如果它们更有可能不选中大部分复选框。
https://stackoverflow.com/questions/55088270
复制相似问题