我在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中,它要求另外一个参数,但是在这种情况下,我无法做到这一点。
你们能请我指导,以便我实现这一目标。
谢谢 兰德(Randheer)
答案 0 :(得分:2)
为<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
<tbody>
</tbody>
</table>
提供一个空的闭包,并使用join()
:
whereRaw()
答案 1 :(得分:0)
使用此
$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();
答案 2 :(得分:0)
我在Laravel 5.8版的DB::raw
中将case end
用于join
语句
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();