简体   繁体   中英

Join in laravel with case and when statement

I've following query in 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;

I'm trying to put this in laravel in following way :

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

but didnt succeed as the mysql query is perfectly working fine but this laravel query wont.

Actually What I think is, there is problem with the Join which I'm putting in laravel it asking for one more parameter but in this case I'm unable to do that.

Can you guys please guide me so that I can achieve this.

Thanks Randheer

Provide an empty closure for join() and use 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();

use this

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

I used the DB::raw for case end statement in join in Laravel Version 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM