5
這是一個搜索函數,它返回每個成員註冊的最近一年。使用查詢生成器的Laravel嵌套連接查詢
我知道它與DB :: raw()調用。但無法讓它與查詢構建器一起工作。
工作代碼:
$query = DB::table('membership as m');
$query->join(
DB::raw(
'(SELECT my.*
FROM membership_years my
INNER JOIN (
SELECT member_id,MAX(membership_year) AS max_my
FROM membership_years
GROUP BY member_id
) my2
ON my.member_id = my2.member_id
AND my.membership_year = my2.max_my
) my'
)
,'m.id','=','my.member_id');
我在查詢生成器代碼嘗試:
$query = DB::table('membership as m');
$query->join('membership_years as my',
function($j1){
$j1->join('membership_years as my2',
function($j2){
$j2->where('my.membership_year','=','MAX(my2.membership_year)')
->on('my.member_id','=','my2.member_id');
}
)->on('m.id','=','my.member_id');
}
);
產生的錯誤是:
調用未定義的方法照亮\數據庫\ Query \ JoinClause :: join()
我不確定這是否是因爲$j2
無法再訪問連接方法?
原MySQL查詢:
SELECT my.membership_year,m.*
FROM membership AS m
INNER JOIN
(
SELECT my1.*
FROM membership_years my1
INNER JOIN
(
SELECT member_id,MAX(membership_year) AS max_my
FROM membership_years
GROUP BY member_id
) my2
ON my1.member_id = my2.member_id
AND my1.membership_year = my2.max_my
) my
ON m.id = my.member_id
ORDER BY m.id ASC