samedi 6 octobre 2018

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire