mysql - 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 的查询生成器来做到这一点?(不是口才)
解决方案
就像是:
$cars = \DB::table('Foo')->take(2)->join('Bar', 'Bar.car_id', '=', 'Foo.id')
->select('Foo.car', 'Bar.color')
->get();
不工作?
推荐阅读
- javascript - 如何从 discord API 中获取 Avatar?
- java - 我可以从 /info/{login} 获得价值吗?
- html - 将图标移至列表左侧
- firebase - 提供者从流中获取价值的延迟
- python - 在我的绘图上格式化 DateTime 轴(Python)
- android - 在 kotlin android 中使用 var 或 val?
- mysql - 如何在 MySQL 中使用 LIKE 而不删除清理?
- django - Django Heroku 部署未找到模块
- python - Django静态文件未加载
- debugging - JetBrains Rider 不评估表达式