我有/
模型,User
与User
有n-n关系。在这种情况下,数据透视表称为Widget
。 dashboards
表包含以下列:
dashboard
,x
,y
和widget_id
。
我正在尝试Eager Load the Dashboard表,以便前端可以在检索user_id
时检索它。
我的User
模型基本上看起来像这样(排除其他关系):
User
class User extends Authenticatable implements AuthenticatableUserContract {
use Notifiable, Loggable, SoftDeletes, HasPolicy;
protected $fillable = [
'email',
'role_id',
'permissions',
'disallowed',
];
protected $hidden = [
'google_token',
];
protected $with = [
'widgets', //breaks code
];
public function widgets() {
return $this->belongsToMany(Widget::class, 'dashboards')->withPivot(['x', 'y']);
}
位以某种方式破坏了应用程序,阻止了protected $with
的身份验证。它以某种方式腐蚀了User
,但我不明白为什么。我在其他一些模型中使用User
完全相同,所以我不认为我错了。
它引发的错误是protected $with
这将引用这行代码Call to a member function cannot() on null
。如果我没有将if( Auth::user()->cannot('read', $policyClass )
放入其中,请通过罚款..
HasPolicy.php:
$with
为什么namespace App\Traits;
use Auth;
use Illuminate\Contracts\Auth\Access\Gate;
trait HasPolicy {
protected static function bootHasPolicy() {
static::loaded( function ($model) {
foreach ($model->with as $relation) {
$policyClass = get_class($model->$relation()->getRelated());
if( Auth::user()->cannot('read', $policyClass ) && app(Gate::class)->getPolicyFor($policyClass) ) {
unset($model->with[array_search($relation, $model->with)]);
}
}
});
}
public function newFromBuilder($attributes = [], $connection = null) {
$instance = parent::newFromBuilder($attributes, $connection);
$instance->fireModelEvent('loaded');
return $instance;
}
/**
* Register a loaded model event with the dispatcher.
*
* @param \Closure|string $callback
* @param int $priority
* @return void
*/
public static function loaded($callback) {
static::registerModelEvent('loaded', $callback);
}
}
会阻止$with
进行身份验证?我应该看什么?