使用 Laravel 范围避免歧义

Tom*_*ena 1 laravel eloquent

我正在 Laravel 中创建一个项目,其中每个公司都有很多部门……每个部门都有一定数量的位置,每个位置都分配了设备!

不同的公司可能使用这个平台,我创建了一个全局范围,基本上通过company_id以下方式过滤结果:

class CompanyScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        return $builder->where('company_id', auth()->user()->company_id);
    }
}
Run Code Online (Sandbox Code Playgroud)

一切都很好,它可以正确过滤,直到我尝试实现以下目标:

Departments::withCount(['locations','devices'])->get();
Run Code Online (Sandbox Code Playgroud)

在这一点上我得到,指出该栏的错误company_id是不明确的。这是发生,因为表departmentslocation并且devices都有一列company_id,并使用范围不指定表名时,最终的查询。

有没有办法将表名添加到范围条件中?

Tom*_*ena 5

嗨,以防万一有人在将来发现疑问...如果您想在 Scope 中指定表,您可以简单地执行以下操作$model->getTable()

class CompanyScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        return $builder->where($model->getTable().'.company_id', auth()->user()->company_id);
    }
}
Run Code Online (Sandbox Code Playgroud)