Laravel在加入后计算行数

时间:2018-05-30 20:21:59

标签: php mysql sql laravel join

我希望按省份获取已加入项目的计数,并将其名称发送到视图中。

这是我的代码:

public function filterByProvince(Request $request)
{

    $province = [];
    foreach ($request->except(['_token']) as $key => $value) {
        $province[$key] = $key;
    }

    $projects = [];
    foreach ($province as $prov){

        $projects[] = DB::table('places')
            ->join('projects', function ($join) use ($prov) {
                $join->on('places.id', '=', 'projects.place_id')
                    ->where('places.province', '=', $prov);
            })->get();

    }


    return view('admin.projects.province', compact(['projects']));

}

1 个答案:

答案 0 :(得分:0)

我不清楚你需要什么,以下是否足够?

public function filterByProvince(Request $request)
{
    $count = array();
    $province = [];
    foreach ($request->except(['_token']) as $key => $value) {
        $province[$key] = $key;
    }

    $projects = [];
    foreach ($province as $prov){

        $result = DB::table('places')
            ->join('projects', function ($join) use ($prov) {
                $join->on('places.id', '=', 'projects.place_id')
                    ->where('places.province', '=', $prov);
            })->get();
        $projects[] = $result;
        $count[$prov] = count($result);

    }


    return view('admin.projects.province', compact(['projects', 'count']));

}