Accessing model attributes to determine relationship
Hi! I feel like I'm missing something totally trivial here but I need some advice about how to use a model's attributes to determine its relationship to another model. I did this in an L4 project by accessing $this->attribute in the relationship function.
i.e.
public function relatedModel()
{
if ($this->version == 1)
{
return $this->hasMany('App\relatedModelChild1');
}
else
{
return $this->hasMany('App\relatedModelChild2');
}
}
In L 5.0 I can't access $this->version.
Qs for you guys:
what's generally the best way to perform this task in laravel?
why can I no longer access $this->version in the relationship function?
It is weird that you can't access $this->version (assuming that version is an attribute of your model). I have relationships that are based on other attributes value and I've only used Laravel 5, 5.1 and 5.2.
You can try these alternative methods to access the version attribute:
About the preferred method to do that, it depends on your database model. You could try using polymorphic relations, so all children would use the same model in Laravel and would be stored in the same table in the database. But this solution depends on how much the two child models differ in the DB.
The reason that I wasn't able to access my version was because I was eager loading and the relationship function was being executed before the model loaded so the attribute array was still empty. I found a workaround that's specific to my solution but it would be great to know what the proper way to deal with that issue is if anyone has any tips!
@gocanto - I ended up running into many limitations with the Eloquent ORM in that project and created a custom model layer. Are you looking for help with something?
Please read about polymorphic relationships, they exist exactly for the use case your code snippet is about -- which is way different from OP's, by the way
Please, do not bump 6 years old threads. The solution presented was for up to Laravel 5.2, which considering the change of version scheme, is 9 versions ago. If needed, open a new thread and say: "Hey I see this other thread X with solution Y, but I think solution Z is better, what do you think?"