首页 > 解决方案 > Laravel 查询构建器仅限制表中的行,即使在连接中这些行必须出现多次

问题描述

我有 2 张桌子:

Foo
| id | car  |
_____________
| 1  |  A   |
| 2  |  B   |
| 3  |  C   |

Bar 
| car_id | color |
__________________
|   1    | red   |
|   1    | green |
|   1    | blue  | 
|   2    | pink  |
|   2    | red   |
|   3    | blue  |

我想将我的加入限制为Foo表(汽车 A 和 B)中的 2 行。为此,我尝试使用此查询:

$cars = \DB::table('Foo')->join('Bar', 'Bar.car_id', '=', 'Foo.id')
        ->select('Foo.car', 'Bar.color')
        ->take(2)
        ->get();

这个查询的问题是我只得到汽车 A 的前两个结果,因为它在Bar表中出现了两次:

Result
[1] A, red
[2] A, green

但我想得到这样的东西:

Result
[1] A, red
[2] A, green
[3] A, blue
[4] B, pink
[5] B, red

我怎样才能通过使用 laravel 的查询生成器来做到这一点?(不是口才)

标签: mysqllaravel-5

解决方案


就像是:

$cars = \DB::table('Foo')->take(2)->join('Bar', 'Bar.car_id', '=', 'Foo.id')
        ->select('Foo.car', 'Bar.color')
        ->get();

不工作?


推荐阅读