[英]Join in laravel with case and when statement
我在Mysql中跟蹤查詢:
SELECT
U.* FROM
`cr_friends` AS `cf` JOIN
`users` AS `U` WHERE
`cf`.`status` = 1
AND
(
CASE
WHEN `cf`.`friend_to` = 1 THEN `cf`.`friend_from` = `U`.`id`
WHEN `cf`.`friend_from` = 1 THEN `cf`.`friend_to` = `U`.`id`
END
) GROUP BY `U`.`id` ORDER BY `cf`.`created` desc;
我試圖通過以下方式將此放入laravel中:
$myFriendsData = DB::table('cr_friends as cf')
->where('cf.status', '=', 1)
->Join('users as U')
->select(
DB::raw(
'(
CASE WHEN cf.friend_to = ' . auth()->user()->id . ' THEN cf.friend_from = U.id END
CASE WHEN cf.friend_from = ' . auth()->user()->id . ' THEN cf.friend_to = U.id END
)'
)
)
->select('U.*')
->orderBy('U.id', 'desc')
->get();
但沒有成功,因為mysql查詢工作正常,但是此laravel查詢不會。
實際上,我認為,Join存在問題,我將其放入laravel中,它要求再輸入一個參數,但是在這種情況下,我無法做到這一點。
你們能指導我,以便我實現這一目標嗎?
謝謝蘭德
為join()
提供一個空的閉包,並使用whereRaw()
:
$myFriendsData = DB::table('cr_friends as cf')
->where('cf.status', '=', 1)
->join('users as U', function() {})
->whereRaw(
'(
CASE
WHEN cf.friend_to = ' . auth()->user()->id . ' THEN cf.friend_from = U.id
WHEN cf.friend_from = ' . auth()->user()->id . ' THEN cf.friend_to = U.id
END
)'
)
->select('U.*')
->orderBy('U.id', 'desc')
->get();
用這個
$myFriendsData = DB::table('cr_friends as cf')
->Join('users as U')
->where('cf.status', '=', 1)
->where(
DB::raw(
'(
CASE WHEN cf.friend_to = ' . auth()->user()->id . ' THEN cf.friend_from = U.id END
CASE WHEN cf.friend_from = ' . auth()->user()->id . ' THEN cf.friend_to = U.id END
)'
)
)
->select('U.*')
->orderBy('U.id', 'desc')
->get();
我在Laravel 5.8版的join
中使用了DB::raw
作為case end
語句
DB::table('users')
->join('settings', function ($join) {
$join->on('settings.id', '=', DB::raw(case when users.type = "admin" then users.admin_setting_id else users.setting_id end'));
})
->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.