用case和when语句加入laravel

csga3l58  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(680)

我在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;

我试着用下面的方式把这个放在拉威尔:

$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查询不会。
实际上我想的是,连接有问题,我把它放入laravel,它要求一个更多的参数,但在这种情况下,我无法做到这一点。
你们能不能指导我,让我能做到这一点。
谢谢randheer

f4t66c6m

f4t66c6m1#

用这个

$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();
cu6pst1q

cu6pst1q2#

提供一个空的封闭 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();
z9gpfhce

z9gpfhce3#

我用了 DB::raw 为了 case end 中的语句 join 在laravel版本5.8中

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();

相关问题