php - Laravel Livewire,初始请求后的全局范围错误
问题描述
我在使用全局范围时遇到问题,我正在开发一个多租户应用程序,我需要根据当前租户/公司来确定数据库范围。租户/公司在请求中,可以像这样访问request()->company()
Controllers 和 Blade 一切正常,现在将我的应用程序升级到 Livewire
TypeError
Argument 1 passed to App\Tenant\Scope\TenantScope::__construct() must be an instance of
Illuminate\Database\Eloquent\Model, null given, called in
D:\laragon\www\vistate\app\Tenant\Traits\ForTenants.php on line 19
为了重现这一点,我有以下
<?php
namespace App\Tenant\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class TenantScope implements Scope
{
protected $company;
public function __construct (Model $company)
{
$this->company = $company;
}
public function apply(Builder $builder, Model $model)
{
return $builder->where($this->company->getForeignKey(), '=', $this->company->id);
}
}
Livewire 版本 2.4.1
这是我的特质
<?php
namespace App\Tenant\Traits;
use App\Tenant\Observers\TenantObserver;
use App\Tenant\Scope\TenantScope;
use App\Tenant\Manager;
trait ForTenants
{
public static function boot()
{
parent::boot();
$manager = app(Manager::class);
static::addGlobalScope(
new TenantScope($manager->getCompany())
);
static::observe(
app(TenantObserver::class)
);
}
}
所以基本上活动租户是在请求中设置的,因此可以在整个应用程序中访问它,就像这样request()->company()
在第一次加载时,一切正常,但此后(水合物)request()->company()
返回空值
请任何建议抬头如何解决这个问题
非常感谢提前
解决方案
protected $company;
public function __construct (Model $company)
{
$this->company = $company;
}
public function apply(Builder $builder, Model $model)
{
return $builder->where($this->company->getForeignKey(), '=', $this->company->id);
}
检查这2件事。尝试更改受保护以公开公司财产。在 Livewire 中,据我所知,protected 和 private 不会持久化数据。在 apply 方法中(也许这无关紧要,但已检查)您与同一公司实例进行比较
public function apply(Builder $builder, Model $model)
{
return $builder->where($this->company->getForeignKey(), '=', $this->company->id);
}
我认为您需要比较 $this->company->getForeignKey(), '=', $model->id,因为您将 $model 实例作为参数传递?
推荐阅读
- discord.py - 如何获得不和谐会员作为用户?
- kubernetes - 用于水平自动缩放的 kubernetes / prometheus 自定义指标
- python - 摆脱数据中已经存在的 ID 组合
- javascript - JS拆分,保持分隔符减去它的第一个字符
- api - 演示停止,如果条件
- python - 遍历文件系统目录结构
- graphql - 有什么方法可以将 GraphQL 查询的多个 Fragment 扩展拆分为多个调用?
- fortran - 在 GPU 上使用 OpenMP+Fortran 减少数组。我得到一个不受支持的动态分配编译时错误
- windows-subsystem-for-linux - 从终端复制选择时,文件中的粘贴不完整(使用 cat)
- ios - 如何设置 UICollectionViewCompositionalLayout 标头的样式以与其子列表 .insetGrouped 布局分开?