Dynamic Relations
-
In my custom module I am trying to create a dynamic relation between my custom model and the user model....
I have the following in my module's config
'User' => [ 'insuree' => function ($self) { return $this->belongsTo('Modules\Brokerquotes\Entities\Insuree', 'id', 'user_id')->first(); }, 'insurer' => function ($self) { return $this->belongsTo('Modules\Brokerquotes\Entities\Insurer', 'id', 'user_id')->first(); } ],
in the User's config I have the following
'relations' => [ // 'extension' => function ($self) { // return $self->belongsTo(UserExtension::class, 'user_id', 'id')->first(); // } 'insuree' => function ($self) { return $this->belongsTo('Modules\Brokerquotes\Entities\Insuree', 'id', 'user_id')->first(); }, 'insurer' => function ($self) { return $this->belongsTo('Modules\Brokerquotes\Entities\Insurer', 'id', 'user_id')->first(); }, ],
However if I
$user->insuree
I get a
null
value....Was there anything else to implement in order to setup dynamic relations for module models?
-
When using built in relationships you don't need the get() or first() methods.
Also you can see $self is being passed in. $this is out of context you want to use $self.
return $self->belongsTo(\Modules\Brokerquotes\Entities\Insurer::class, 'user_id', 'id');
-
Hi,
Yes, pretty much what @Demaestro said.
It's valid to retrieve the result of the builder, but I would not advise since you loose chain options later on.
-
@demaestro said in Dynamic Relations:
When using built in relationships you don't need the get() or first() methods.
Also you can see $self is being passed in. $this is out of context you want to use $self.
return $self->belongsTo(\Modules\Brokerquotes\Entities\Insurer::class, 'user_id', 'id');
@armababy @Demaestro I'm using v3.x version and was told that $this is being resolved ot the proper context. I have sinced removed the parameter but still run into the problem
-
Solved by remove $self parameter and calling
$user->profile()
and not$user->profile