mysql - Laravel 连接表和查询

标签 mysql laravel-5 eloquent

我有 3 张 table 。用户、账户和预订。我已经尝试了三个表连接和年月明智的查询。 [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"

但我需要的早餐、午餐、晚餐的数量是:1。但它显示双倍。

最佳答案

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

$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;
    }

关于mysql - Laravel 连接表和查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35111650/

相关文章:

php - get请求时是否有必要在laravel Controller 中使用htmlspecialchars

php - 在 ModelFactory Laravel 中播种多个自定义行/条目

Mysql删除存储的转义字符

php - Laravel 很棒但是...... HATEOAS 的考虑在哪里?

php - Laravel 5 - 验证多个请求

mysql - 获取两个给定日期之间的数据不会返回任何内容 Eloquent

php - 此集合实例上不存在属性 [title]

mysql - 我可以自动调整数据库中自增字段的值吗?

php - 检查 mySQL 数据库是否有重复的 uid

mysql - 20,000,000 个表自身连接太慢