I'm having a lot of trouble converting the following SQL query to work with Laravel's query builder.

SELECT * FROM gifts 
JOIN giftcategory ON gifts.id = giftcategory.giftid
JOIN giftoccasions ON gifts.id = giftoccasions.giftid
JOIN giftrelationship ON gifts.id = giftrelationship.giftid

WHERE (gifts.gender = 'any' OR gifts.gender = 'male')
AND giftoccasions.occasionid = '2'
AND (giftcategory.categoryid = '0' OR giftcategory.categoryid = '1')
AND giftrelationship.relationshipid = '1'

This query works fine, but I can't get the same results when using Laravel's query builder. I have the following code so far. It is not working correctly at all. I'm thinking the issue could lie with the orWhere part because it seems to be returning results that don't match any of the other where clauses.

$giftQuery = DB::Table('gifts')
->Join('giftcategory', 'gifts.id', '=', 'giftcategory.giftid')
->Join('giftoccasions', 'gifts.id', '=', 'giftoccasions.giftid')
->where('gifts.gender', '=', "male")
->orwhere('gifts.gender', '=', "any")
->where('giftoccasions.occasionid', '=', "2")
->where('giftoccasions.relationshipid', '=', "1")
->Where('giftcategory.categoryid', '=', "0")
->orWhere('giftcategory.categoryid', '=', "1");

推荐答案

要将advanced where与参数分组一起使用:

$giftQuery = DB::table('gifts')
    ->join('giftcategory', 'gifts.id', '=', 'giftcategory.giftid')
    ->join('giftoccasions', 'gifts.id', '=', 'giftoccasions.giftid')
    ->where(function($query) {
        $query->where('gifts.gender', '=', "male")
            ->orWhere('gifts.gender', '=', "any");
    })
    ->where('giftoccasions.occasionid', '=', "2")
    ->where('giftoccasions.relationshipid', '=', "1")
    ->where('giftcategory.categoryid', '=', "0")
    ->orWhere('giftcategory.categoryid', '=', "1");

Laravel相关问答推荐

提交表格后如何在Livewire 3中调度模式窗口?

在postgres/mysqlс中,我可以定义基于json字段的唯一索引吗?

如何在 Laravel 中获取特定月份的最后一个日期?

按回车键时如何防止此功能运行?

单个对象的Eloquent 计数是错误的

mysql 加入 ON 和 AND 到 laravel eloquent

在 laravel 5.3 中截断的错误日志(log)

Laravel:使用 Input::old 时 textarea 不会重新填充

在 laravel 中动态更改时区

判断 Laravel 模型表中是否存在列,然后应用条件

如何在同一行显示 Laravel artisan 命令输出?

使用限制排队 Guzzle 请求

Laravel 动作未定义

Laravel5如何将数组传递给查看

改变模式生成器中的列长度?

在 Laravel artisan 命令中使用详细

在 laravel 的自定义路径中创建模型

Laravel 验证存在于不存在的地方

Carbon解析到 ISO8601

如何判断是否连接到 Laravel 4 中的数据库?