拉拉维尔自引用范围



是否可以在范围内应用自引用标准?

我需要编写一个范围,允许用户检索与其帐户相关的供应商。

class Account extends Model
{
public function supplier(): BelongsTo
{
return $this->belongsTo(self::class, 'supplier_id');
}
public function customers(): HasMany
{
return $this->hasMany(self::class, 'supplier_id');
}
}

我尝试了以下方法:

class SupplierAccessScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
/*
* Join accounts onto itself - does not seem to work
*/
$builder->join('accounts as a2', 'a2.id', '=', 'accounts.supplier_id');
// Reference using own column - produces error
$builder->where('accounts.id', 'accounts.supplier_id');
}
}

看起来我做错了。一旦我意识到我需要返回额外的结果而不是添加额外的列,我就减少了所需的 SQL 查询:

SELECT accounts.id
FROM accounts
WHERE accounts.id IN ([account IDs])
OR accounts.id IN (SELECT accounts.supplier_id FROM accounts WHERE accounts.id IN([account ID]))

所以我的全球范围最终看起来像这样:

public function apply(Builder $builder, Model $model)
{
if (!auth()->guard('admin')->check() && auth()->user()) {
$accountIds = AccountAccess::where('user_id', auth()->user()->id)->get()->pluck('account_id');
$builder->where(function ($builder) use ($accountIds) {
$builder->whereIn('accounts.id', $accountIds);
$builder->orWhereIn('accounts.supplier_id', $accountIds);
$builder->orWhereRaw('accounts.id IN (SELECT supplier_id FROM accounts WHERE id IN (?))', $accountIds);
});
}
return $builder;
}

最新更新