提前加入laravel 5

advance join in laravel 5

我有一个usertable这样的

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

transfer table 这样的

+----+--------------+------------+--------+
| 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();

但是这样做只会给我对应于 from_user_idfirst_namelast_name 。但我也想要相应的 first_namelast_name 对应于 to_user_id。我怎样才能得到它们?

我想要的输出table

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

这是生成上述 table 所需的 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

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

$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();

这是我尝试为您的 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 table 的双连接添加别名,以及如何使用 DB::raw() 访问 MySQL CONCAT 函数。