【问题标题】:appending like data when Joining two tables when two columns of one table refer to a third one in Laravel当一个表的两列引用Laravel中的第三个时,在连接两个表时附加类似的数据
【发布时间】:2021-02-03 06:17:34
【问题描述】:

我有三张桌子。 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 数据表中,所以如果我能够通过更改我的查询来完成此操作,那么这将变得不那么复杂。

【问题讨论】:

    标签: php mysql laravel yajra-datatable


    【解决方案1】:

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

    $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 关键字选择在两个表中具有匹配值的记录。

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      相关资源
      最近更新 更多