5

最近 Laravel 发布了 5.3 版本。

以下链接中有一些从 5.2 到 5.3 的升级说明: https ://laravel.com/docs/5.3/upgrade#upgrade-5.3.0

Eloquent 作用域现在尊重作用域约束的前导布尔值。例如,如果您以 orWhere 约束开始您的范围,它将不再转换为正常的 where。如果您依赖此功能(例如,在循环中添加多个 orWhere 约束),您应该验证第一个条件是正常的 where 以避免任何布尔逻辑问题。

如果您的范围以 where 约束开始,则无需执行任何操作。请记住,您可以使用查询的 toSql 方法验证您的查询 SQL:

这似乎使事情变得更加困难,升级只会增加限制。

我们有一个内部包,为了使代码尽可能简单和整洁,有一部分依赖于使用 orWhere() 开始查询,并在递归方法中利用了它以及闭包概念。如您所知,递归方法最好保持简短和简单。

根据现在的升级说明,它肯定会在 Laravel 5.3 上失败

我只是想知道是否有人知道为什么要删除此行为的原因?

谢谢!

更新:

我已经将我们的系统迁移到 Laravel 5.3。我确认这仅在 Eloquent builder 中受到影响,而在 Query Builder(以前称为“Fluent Builder”)中不受影响。

甚至提交(这是一个巨大的变化)也只在 Eloquent\Builder 上。 https://github.com/laravel/framework/issues/14829

无论如何,为了安全起见,我确实建议进行相应的调整。这就是我们所做的,尽管我们知道它并没有破坏我们的代码(截至今天)。

4

2 回答 2

7

我相信原因正是这个拉取请求:https ://github.com/laravel/framework/pull/12918

有人想使用这样的范围:

User::approved()->orActive();

在这种情况下,如果orActive范围定义如下:

public function scopeOrActive($q) {
   return $q->orWhere('active',1)
}

范围approved定义如下:

public function scopeApproved($q) {
   return $q->where('approved',1)
}

在 laravel 5.2 中,它将解决:

where approved = 1 AND active = 1

在 Laravel 5.3 中,它解决了:

where approved = 1 OR active = 1

所以这是有道理的,但是我从未使用过以orWhere

于 2016-07-13T17:58:31.287 回答
1

这是一种将多个 orWhere 子句与布尔值一起使用的方法。假设您要进行如下查询:

select * from users where active = 1 and (user_type = 1 or user_type = 2 or user_type = 3);

但是我们不一定总是希望所有的 user_types 都在查询中,即我们有一些布尔值来决定哪些应该存在。这可以像这样实现:

$includeOne = true;
$includeTwo = false;
$includeThree = true;
$query = User::where('active', 1)
    ->where(function($q) use ($includeOne, $includeTwo, $includeThree) {
        $q->when($includeOne, function($query) {
            return $query->orWhere('user_type', 1);
        })
        ->when($includeTwo, function($query) {
            return $query->orWhere('user_type', 2);
        })
        ->when($includeThree, function($query) {
            return $query->orWhere('user_type', 3);
        });
    })->get();
于 2017-10-05T13:07:03.947 回答