簡體   English   中英

當一個表的兩列引用 Laravel 中的第三個時,在連接兩個表時附加類似的數據

[英]appending like data when Joining two tables when two columns of one table refer to a third one in Laravel

我有三張桌子。 items、authors 和 author_item 將 author_id 與 item_id 配對。

我在加入時使用第三個表成功地從項目和作者中選擇了我需要的一切。

我遇到的問題是,有時有兩三個作者 go 有一個項目,我想 append 所有匹配的作者到一個項目行。

$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 關鍵字選擇兩個表中具有匹配值的記錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM