提前加入laravel 5

时间:2015-08-19 08:53:40

标签: mysql laravel-5 query-builder

我有一个像这样的user

+----+------------+-----------+---------+
| id | first_name | last_name | address |
+----+------------+-----------+---------+
| 1  |     x      |     y     |    z    |
| 2  |     a      |     b     |    c    |
| 3  |     p      |     q     |    r    |
+----+------------+-----------+---------+

和这样的transfer

+----+--------------+------------+--------+
| id | from_user_id | to_user_id | amount |
+----+--------------+------------+--------+
| 1  |      1       |     2      |   20   |
| 2  |      2       |     1      |   10   |
| 3  |      3       |     2      |   10   |
+----+--------------+------------+--------+

现在我可以像这样使用连接查询

 $transfer = DB::table('users')
            ->join('transfers', function($join) {
                $join->on('users.id', '=', 'transfers.from_user_id');
            })
            ->select('users.first_name','users.last_name', 'transfers.amount', 'transfers.date')
            ->get();

但执行此操作会为我提供与first_name对应的last_namefrom_user_id。但我也希望相应的first_namelast_name分别对应to_user_id。我怎么能得到它们?

我想要的输出表

+---------+---------+--------+
| sent_by | sent_to | amount |
+---------+---------+--------+
|   xy    |   ab    |   20   |
|   ab    |   xy    |   10   |
|   pq    |   ab    |   10   |
+---------+---------+--------+

这是生成上表所需的MySQL查询。如您所见,它需要2个内连接:

SELECT CONCAT(u1.first_name, u1.last_name), CONCAT(u2.first_name, u2.last_name), t.amount
FROM transfer t INNER JOIN user u1
ON t.from_user_id = u1.id
INNER JOIN user u2
ON t.to_user_id = u2.id

2 个答案:

答案 0 :(得分:2)

在连接表上使用别名。 希望有所帮助。

$transfer = DB::table('transfers')
    ->join('users as senders', function($join) {
        $join->on('transfers.from_user_id', '=', 'senders.id');
    })
    ->join('users as receivers', function($join) {
        $join->on('transfers.to_user_id', '=', 'receivers.id');
    })
    ->select('senders.first_name','senders.last_name', 'receivers.first_name','receivers.last_name', 'transfers.amount', 'transfers.date')
    ->get();

答案 1 :(得分:2)

以下是我尝试使用Laravel查询的解决方案:

$transfer = DB::table('transfer')
                     ->join('user as u1', 'transfer.from_user_id', '=', 'u1.id')
                     ->join('user as u2', 'transfer.to_user_id', '=', 'u2.id')
                     ->select(DB::raw('CONCAT(u1.first_name, u1.last_name) AS sent_by'), 
                              DB::raw('CONCAT(u2.first_name, u2.last_name) AS sent_to'),
                              'transfer.amount as amount')
                     ->get();

诀窍是知道如何在transferuser表中包含双连接的别名,以及使用DB::raw()访问MySQL CONCAT函数