Laravel在javascript中从控制器获取两个值数组计数

时间:2018-02-16 14:23:26

标签: javascript json laravel charts highcharts

我有一个查询,如果性别=" mal"和女性"。

$users[] =  User:: whereIn('gender',array('mal', 'female'))->count()->get();
return view('/',compact('users[]'));

这些计数显示在条形图

function drawStacked() {
var genders[] = {{ $users[] }}
var data = google.visualization.arrayToDataTable([
    ['Element', '', { role: 'style' }, { role: 'annotation' } ],
    ['Mal', '#000', genders[0]],
    ['Female', '#000', genders[1]],
 ]);
}

但他只向我展示了性别 mal

的数量

3 个答案:

答案 0 :(得分:1)

您需要执行两个查询:

$maleCount = User::where('gender', 'male')->count();
$femaleCount = User::where('gender', 'female')->count();
return view('/', compact('maleCount', 'femaleCount'));

答案 1 :(得分:0)

这对于Alexey Mezenin的解决方案来说非常好,但是我想在一个地方重新组合并返回数组并在javascript中显示它,例如:genders[0] for mal and genders[1] for female

答案 2 :(得分:0)

您只需将Alexey解决方案的结果放入如下数组:

$counts = [
    'male' => User::where('gender', 'male')->count(),
    'female' => User::where('gender', 'female')->count()
];

return view('/', compact('counts'));

然后您可以在以下视图中访问它们:

$counts['male']
// or
$counts['female']