laravel与3表

时间:2016-11-30 12:05:10

标签: laravel-5

嗨我想从3桌上查询

用户:

+----+-----------+
| id |   name    |
+----+-----------+
|  1 | Denny     |
|  2 | Agus      |
|  3 | Dini      |
|  4 | Angel     |
+----+-----------+

History_Education

+----+-----------+-------------+
| id |   userId  | educationId |
+----+-----------+-------------+
|  1 |  1        | 1           |
|  2 |  1        | 2           |
|  3 |  2        | 1           |
|  4 |  2        | 2           |
+----+-----------+-------------+

教育

+----+-----------+----------+
| id |   level   |   Name   |
+----+-----------+----------+
|  1 | 1         |   SD     |
|  2 | 2         |   SMP    |
|  3 | 3         |   SMA    |
|  4 | 4         |   S1     |
+----+-----------+----------+

如何使用laravel Eloquent查询以获取Level DESC的最新用户教育订单 预期:

+----+-----------+----------------------+
| id |   Name    |   Latest_Education   |
+----+-----------+----------------------+
|  1 | Denny     |   SMP                |
|  2 | Agus      |   SMP                |
|  3 | Dini      |    -                 |
|  4 | Angel     |    -                 |
+----+-----------+----------------------+

在正常查询中: 选择id,name,(从教育E内部联接中选择E.name,在E.id = HE.education_id,其中HE.userId = U.id限制1级由E.level DESC订购)来自USER U

如何翻译成laravel eloquent?

1 个答案:

答案 0 :(得分:0)

快速回答是使用查询构建器 - 您的查询需要稍微更改以匹配您的问题中列出的表名和列:

$result = DB::table('user')
    ->select([
        'id',
        'name',
        DB::raw("(select E.name from Education E inner join History_Education HE on E.id = HE.educationId where HE.userId = user.id order by E.level DESC limit 1) as latest_education")
    ])
    ->get();