当一个表的两列引用 Laravel 中的第三列时,在加入两个表时附加类似的数据

问题描述

我有三张桌子。 items、authors 和 author_item 将 author_id 与 item_id 配对。

我在加入时使用第三个表成功地从项目和作者中选择了我需要的一切。

我遇到的问题是有时有两个或三个作者与一个项目相关,我想将所有匹配的作者附加到一个项目行。

$publications = \DB::table('items')
   ->select('items.pub_number','items.title','authors.first_name','authors.last_name','items.published_date','items.updated_at')
   ->leftjoin('author_item','items.id','=','author_item.item_id')
   ->leftjoin('authors','author_item.author_id','authors.id')
   ->where('items.is_product',false); ```

对于一个可见的表示,我将在下面演示。

我愿意

| Pub # | Title | Authors      | Published  | Revision  |
| ------| ------| -----------  | 1989-09-03 | 2020-10-05|
| 138   | beledo|Jaeden Pouros | 1989-09-03 | 2020-10-05|
| 138   | beledo|Jennifer Lexy | 1989-09-03 | 2020-10-05|
| 145   | argade|Alex Johnson  | 1989-09-03 | 2020-10-05|

成为

| Pub # | Title | Authors                     | Published  | Revision  |
| ------| ------| --------------------------- | 1989-09-03 | 2020-10-05|
| 138   | beledo|Jaeden Pouros,Jennifer Lexy | 1989-09-03 | 2020-10-05|
| 145   | argade|Alex Johnson                 | 1989-09-03 | 2020-10-05|

这会被查询到 Yajra 数据表中,所以如果我能够通过改变我的查询来实现这一点,那么这将使这变得不那么复杂。

解决方法

如果你只需要三个表中匹配的行,你应该使用内连接

$publications = \DB::table('items')
 ->select('items.pub_number','items.title','authors.first_name','authors.last_name','items.published_date','items.updated_at')
   ->join('author_item','items.id','=','author_item.item_id')
   ->join('authors','author_item.author_id','authors.id')
   ->where('items.is_product',false);

因为 LEFT JOIN 关键字返回左表(author_item,authors)中的所有记录,以及右表中匹配的记录。如果没有匹配,则结果为右侧的 NULL 和 INNER JOIN 关键字选择在两个表中具有匹配值的记录。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...