使用 case 和 when 语句加入 laravel

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 它要求再提供一个参数,但在这种情况下我无法做到这一点。

你们能指导我吗,这样我就可以做到这一点。

谢谢 兰德赫

使用这个

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

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

我在 Laravel 版本 5.8

中的 join 中使用了 DB::raw for 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();