简体   繁体   中英

Need help to convert SQL query to Laravel eloquent

I have this SQL query:

SELECT * FROM `user` WHERE `id` IN(
    SELECT  DISTINCT if(`sender_id`='2',`receiver_id` ,`sender_id`) AS `id`
    FROM    `message`
    WHERE   (`receiver_id`  = '2' OR `sender_id` = '2')
    )

I need convert to Laravel eloquent. The problem is, I do not know how to convert the IF function.

$subquery = DB::table('message')
    ->selectRaw("if(sender_id = ?, receiver_id, sender_id) AS id")
    ->distinct()
    ->where(function($query){
        $query
            ->where('receiver_id', '?')
            ->orWhere('sender_id', '?');
    })
    ->toSql();

$query = DB::table('user')
    ->whereRaw('id IN (' . $subquery . ')', [2, 2, 2])
    ->get();

在此处输入图片说明

User::whereIn('id', Message::distinct()->select(DB::raw('if(sender_id=2, receiver_id, sender_id) as id'))->where( 
            function( $query ) {
                $query
                ->where('receiver_id', 2)
                ->orWhere('sender_id', '2');
            }
        ))->toSql();

to use if condition in sql statement you can use DB::raw method :)

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