Laravel加入表和查询

时间:2016-01-31 08:05:05

标签: mysql laravel-5 eloquent

我有3张桌子。用户,帐户和预订。我已经尝试了三个表加入和年和月明智的查询。 [3表格图] [1]

但查询预订计算显示错误。它显示出双倍数量。

$january = DB::table('users')
        ->join('bookings', 'users.id', '=', 'bookings.user_id')
        ->join('accounts', 'users.id', '=', 'accounts.user_id')
        ->orderBy('users.room_id','asc')
        ->groupBy('users.id')
        ->whereYear('bookings.bookingdate','=', '2016')
        ->whereMonth('bookings.bookingdate','=','01')
        ->whereYear('accounts.accountdate','=', '2016')
        ->whereMonth('accounts.accountdate','=','01')
        ->select('users.*',
            DB::raw("COUNT(case when bookings.breakfast='on' then 1 else null end) AS t_breakfast"),
            DB::raw("COUNT(case when bookings.lunch='on' then 1 else null end) AS t_lunch"),
            DB::raw("COUNT(case when bookings.dinner='on' then 1 else null end) AS t_dinner"),
            DB::raw("SUM(accounts.amount) AS t_amount")
        )
        ->get();

    dd($january);

我的帐户表是: Accounts Table 我的预订表是: Bookings Table

当我运行此查询时,显示:

+"t_breakfast": "2"
+"t_lunch": "2"
+"t_dinner": "2"
+"t_amount": "22.00"

但是我需要t_breakfast,t_lunch,t_dinner数量是:1。但是它显示了双倍。

1 个答案:

答案 0 :(得分:0)

当我尝试一个查询时,我没有解决这个问题。然后我尝试了两个查询并解决了它。

$data = DB::select("SELECT users.id, users.name , users.picture, users.room_id,
        SUM(CASE WHEN bookings.breakfast='on' THEN 1 ELSE 0 END) AS t_b ,
        SUM(CASE WHEN bookings.lunch='on' THEN 1 ELSE 0 END) AS t_l ,
        SUM(CASE WHEN bookings.dinner='on' THEN 1 ELSE 0 END) AS t_d FROM `users`
    INNER JOIN
    `bookings` ON users.id=bookings.user_id AND
    MONTH(bookings.bookingdate) = $month AND
    YEAR(bookings.bookingdate) = $year

    GROUP BY users.id
    ORDER BY users.room_id ASC");

    $datas = [];
    $data = json_decode(json_encode($data),true);
    foreach ($data as $key => $value) {
        $x = [];
        $x = $value;
        $x['exp'] = Account::where('user_id',$x['id'])->whereMonth('accountdate','=',$month)->whereYear('accountdate','=',$year)->sum('amount');
        $datas[] = $x;
    }

    $total_t_b = $total_t_l = $total_t_d = $total_exp = 0;
    foreach ($datas as $data) {
        $total_t_b += $data['t_b'];
        $total_t_l += $data['t_l'];
        $total_t_d += $data['t_d'];
        $total_exp += $data['exp'];

    }
    $g_total = $total_t_b + $total_t_l + $total_t_d;

    if($g_total <= 0) {
        $perbookingprice = 0;
    } else {
        $perbookingprice = $total_exp / $g_total;
    }