将此SQL查询作为Eloquent语句的最佳方法是什么?

时间:2015-03-25 10:48:02

标签: mysql laravel laravel-4

我需要跟随sql语句转换为Laravel Eloquent。尝试了几种方法并且确实失败了。

SELECT * FROM `conversations` where `type` = 'open' 
AND `sender_id`=2 AND ((`deleted_by_sender` IS NULL ) 
AND (`deleted_by_sender` IS NULL  OR `deleted_by_receiver` IS NULL  )) 
OR `receiver_id` = 2 AND ((`deleted_by_sender` IS NULL ) 
AND (`deleted_by_sender` IS NULL  OR `deleted_by_receiver` IS NULL  ))

提前谢谢。

2 个答案:

答案 0 :(得分:1)

你可以用这种方式在eloquent中执行查询,我假设你有一个名为Conversation的模型

Conversation::where('type', 'open')
->where('sender_id', 2)
->whereNull('deleted_by_sender')
->where(function ($query) {
    return $query->whereNull('deleted_by_sender')
        ->orWhereNull('deleted_by_receiver');
})->orWhere('receiver_id', 2)
->whereNull('deleted_by_sender')
->where(function ($query) {
    return $query->whereNull('deleted_by_sender')
        ->orWhereNull('deleted_by_receiver');
})->get();

这些代码未经测试,直接从您的SQL查询中翻译

答案 1 :(得分:0)

如果我理解正确,你期待这样:

SELECT * FROM `conversations` 
 WHERE `type` = 'open' 
   AND ( `deleted_by_sender` IS NULL OR `deleted_by_receiver` IS NULL )
   AND ( ( `sender_id`=2 AND `deleted_by_sender` IS NULL )
         OR
         ( `receiver_id` = 2 AND `deleted_by_receiver` IS NULL )
       )