Laravel 5渴望加载用户关系

时间:2017-05-04 10:06:22

标签: php laravel eager-loading

我有/模型,UserUser有n-n关系。在这种情况下,数据透视表称为Widgetdashboards表包含以下列:

dashboardxywidget_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进行身份验证?我应该看什么?

堆栈跟踪: https://pastebin.com/16J3cptM

0 个答案:

没有答案