我通过auth(( -> user(( - dbname设置数据库连接在模型中使用此功能可根据需要起作用
public function __construct() {
$this->connection = auth()->user()->dbname;
}
现在我想观察创建,更新等的模型。我试图使用
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$itemIds = $model->item_ids;
... update another model based on the $itemIds
});
但是Nova没有识别静态::创建功能因此,我创建了一个观察者(我认为是一个更好的选择(,但是当观察者称为
时,当观察者被称为 时auth(( -> user(( -> dbName属性
为什么观察者不识别auth?
这可能是因为没有身份验证的用户而引起的。尝试倾倒,看看它给您扔了什么。
public function __construct() {
// Should throw an User model OR null.
dd(auth()->user());
// Alternatively, you could use the Logger
Log::info(json_encode(auth()->user()));
$this->connection = auth()->user()->dbname;
}
如果auth()->user()
是null
,则没有登录用户,并且您可能已经猜到了,null
是非对象。
感谢您的建议,但没有人对我有用。我放弃了诺瓦的观察员。我使用了boot((函数。这就是我设置Milti租户的方式。
在_constructor中我添加了此
public function __construct() {
parent::__construct(); // needed before boot would fire
$this->connection = auth()->user()->dbname;
}
然后我的boot((函数成为观察者
protected static function boot()
{
parent::boot();
static::creating(function($item) {
$item->event_id = Event::currentEventID();
});
}