【问题标题】:Using multiple where clauses with laravel query builder在 laravel 查询构建器中使用多个 where 子句
【发布时间】:2015-06-03 05:19:11
【问题描述】:

我在转换以下 SQL 查询以使用 Laravel 的查询构建器时遇到了很多麻烦。

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'

这个查询工作正常,但使用 Laravel 的查询生成器时我无法得到相同的结果。到目前为止,我有以下代码。它根本无法正常工作。我认为问题可能出在 orWhere 部分,因为它似乎返回的结果与任何其他 where 子句都不匹配。

$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");

【问题讨论】:

  • 如果您对我在下面的回答感到满意,您可以接受:)

标签: php mysql laravel laravel-5


【解决方案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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-19
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    相关资源
    最近更新 更多