![](/img/trans.png)
[英]Left Join - Select ALL from left table but select only the latest from right table
[英]Laravel 2 table join with all from left table merged with members of the right table with a given FK value
我在Laravel中有兩個表,我正在尋求將它們合並在一起,但是,我想返回第一個表的每個單個值(無重復項)以及僅第二個表的FK值為2的值。沒有FK為2的條目,它以空值連接。
為了使我的問題更清楚一點,可以說我們有下表:
TV Shows Table
ID | Show
1 | First Show
2 | Second Show
3 | Third Show
Favorites Table
Show_ID | Member_ID
1 | 1
3 | 1
1 | 2
2 | 2
當我加入成員ID為2的表時(不考慮加入的“ Show_ID”列),我希望將它們合並為如下所示的結果集:
Merged Table
ID | Show | Member_ID
1 | First Show | 2
2 | Second Show | 2
3 | Third Show | null
謝謝。
不是100%我了解,所以希望這是您要尋找的。
我重命名了一些列名,以使事情更清楚一些。
DB::table('shows')
->select(
'shows.id as show_id',
'shows.name as show_name',
'member.id as member_id'
)
->leftJoin('favourites', 'shows.id', '=', 'favourites.show_id')
->get();
左聯接將允許member_id
null
(如果member_id
中不存在該聯接)。
您可以添加此選項以將成員ID限制為兩個:
DB::table('shows')
->select(
'shows.id as show_id',
'shows.name as show_name',
'member.id as member_id'
)
->leftJoin('favourites', 'shows.id', '=', 'favourites.show_id')
->where('member.id', 2)
->get();
我自己解決了。 我需要像這樣進行功能連接:
DB::table('shows')
->leftJoin('favorites', function($q) use $memberID)
{
$q->on('shows.ID', '=', 'favorites.show_ID')
->where('favorites.member_ID', '=', $memberID);
})->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.