【问题标题】:Laravel 5.8 apply global scope on newQuery like 4.2 didLaravel 5.8 像 4.2 一样在 newQuery 上应用全局范围
【发布时间】: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”?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    它没有记录,但您可以使用“扩展”而不是“应用”。 'extend' 在查询开始时触发,因此 where 子句在前。

    在我的作用域类中:

      /**
       * @param Builder $builder
       * @return void
       */
      public function extend(Builder $builder)
    

    【讨论】:

      【解决方案2】:

      要将全局范围分配给模型,您应该覆盖给定模型的booted 方法并使用addGlobalScope 方法:

      protected static function booted()
      {
          static::addGlobalScope(new TenantScope);
      }
      

      【讨论】:

      • 是的,这就是我正在做的。执行此操作时,范围将应用于“获取”。我需要将它应用于“newQuery”,因此“where”子句是第一个条件,而不是最后一个条件。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 2015-12-02
      • 2014-11-23
      • 1970-01-01
      • 2018-05-07
      • 2015-07-06
      相关资源
      最近更新 更多