Laravel Query连接多表

时间:2015-12-28 16:00:22

标签: php mysql sql database laravel

Hello this is my example database :
    users:
    id
    username
    .
    .


    starter:
    id
    user_id
    is_cycle

    bronze:
    id
    user_id
    is_cycle

    diamod:
    id
    user_id
    is_cycle

表,Starter Bronze,Diamon等:拥有is_cycle 0或1 我想计算每个用户ID,表中的起始编号为is_cycle = 1,所有表都是如此 结果:

username    Starter        Bronze    Diamond

admin       2              3               2
demo        2              1               0
.
.

 
example :

users:

id       username      ....
1   admin
2   demo
.
.
.


Starter :

id user_id  is_cycle
1   1   1
2   2   0
3   1   1
4   2   1
5   1   1

there are : 
user_id=1 have 3 cycle
user_id=2 have 1 cycle

Bronze:

id user_id  is_cycle
1   1   1
2   1   0
3   1   0
4   2   1
5   2   1

there are :
user_id=1 have 1 cycle
user_id=2 have 2 cycle



Result of query :

username   Starter   Bronze 
1       3   1
2       1   2

其实我正在使用Laravel 5.1。我将感谢每一条评论。谢谢

实际上:

$starter = DB::table('users')
->join('matrix_starter', function ($join) {
    $join->on('users.id', '=', 'matrix_starter.user_id')
        ->where('matrix_starter.is_cycle', '=', 1);
})
->groupBy('users.id')
->get([
    'users.username', 
    DB::raw('count(matrix_starter.is_cycle) as starter')
]);

$builder = DB::table('users')
->join('matrix_bronze', function ($join) {
    $join->on('users.id', '=', 'matrix_bronze.user_id')
        ->where('matrix_bronze.is_cycle', '=', 1);
})
->groupBy('users.id')
->get([
    'users.username', 
    DB::raw('count(matrix_bronze.is_cycle) as bronze')
]);

0 个答案:

没有答案