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

标签 php laravel laravel-5.5 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

最佳答案

您可以使用函数来定义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);

希望对你有帮助

关于php - Laravel:如何在一个查询中编写两个查询并从数据库获取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48265574/

相关文章:

php - 防止垃圾邮件的 php 页面的功能

php - AWS S3 无法通过 PHP SDK 删除存储桶中的对象

php - Laravel API 资源 : How to return infinite nested array of categories with their children?

php - Laravel Eloquent 获取具体关系

Laravel 如何从子域 URL 中删除 "api"前缀

php - Laravel 5.5 - Eloquent - 从具有 "microseconds"字段的 MySQL 表中检索 "datetime(6)"

php - mysql多表全文查询问题?

php - 为什么 if/else vs. or/exit 在 PHP 中?

javascript - 单击按钮时删除正确的行

laravel-5.5 - PHP 解析错误 : syntax error, helpers.php 233 中的意外 '?'