Laravel:如何在一个查询中编写两个查询并从数据库中获取结果?

时间:2018-01-15 15:04:51

标签: php laravel eloquent laravel-5.5 laravel-eloquent

我有获取当前用户的所有已删除消息的示例代码:

$query1 = $inbox->where('recipient', $user_id)
                ->where('trashed_in_recipient', 1)
                ->where('show_in_recipient', '!=', 1)
                ->orderBy('created_at', 'desc')
                ->paginate($paginate);

$query2 = $inbox->where('sender', $user_id)
                ->where('trashed_in_sender', 1)
                ->where('show_in_sender', '!=', 1)
                ->orderBy('created_at', 'desc')
                ->paginate($paginate);

如何在一个中写入两个查询并获得最终结果?

表格结构:

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用功能定义WHERE组:

$query = $inbox->where(function($query) use ($user_id) {
    $query->where('recipient', $user_id);
    $query->where('trashed_in_recipient', 1);
    $query->where('show_in_recipient', '!=', 1);
})->orWhere(function($query) use ($user_id) {
    $query->where('sender', $user_id);
    $query->where('trashed_in_sender', 1);
    $query->where('show_in_sender', '!=', 1);
})->orderBy('created_at', 'desc')
  ->paginate($paginate);

我希望这有助于你