需要帮助将SQL查询转换为雄辩的Laravel

时间:2018-12-11 11:36:39

标签: php mysql laravel eloquent

我有这个SQL查询:

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')
    )

我需要雄辩地转换为Laravel。问题是,我不知道如何转换IF函数。

2 个答案:

答案 0 :(得分:0)

Map

enter image description here

答案 1 :(得分:0)

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

要在sql语句中使用if条件,可以使用DB::raw方法:)