【发布时间】:2020-05-22 02:58:40
【问题描述】:
我正在将一个 laravel 4.2 项目升级到 5.8。
在 4.2 中,我使用全局范围特征自动将 where 条件添加到我的模型中。 where 条件将添加到“newQuery”上,并且是第一个 where 条件。
现在在 5.8 中,我使用新方式添加了全局范围,它不会从“newQuery”的范围中添加 where 条件,而是通过将 where 条件附加到查询来将全局范围条件应用于“get” .这与我的数据库索引不匹配,我不能这样做,我需要将我的全局范围应用于“newQuery”。
class TenantScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$builder->where($model->getQualifiedTenantColumn(), '=', \idweb\helpers\SessionHelper::getTenantId());
$builder->whereNull($model->getQualifiedDateDeletedColumn());
}
}
// when I do this:
$q = \myapp\MyModel::query();
// the following test should be true with my two where conditions applied from the scope
// with laravel 5.8, this fails, the scope has not been applied yet
$this->assertEquals(2, count($q->newQuery()->wheres));
$q->where('cat', 'dog');
$list = $q->get();
// this uses db query, which is wrong
select * from mymodel where cat=dog and tenant=1 and date_deleted is null;
// the query needs to be by having the scope applied on newQuery, not get:
select * from mymodel where tenant=1 and date_deleted is null and cat=dog;
如何像 4.2 一样将我的范围应用于“newQuery”?
【问题讨论】: