Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Getting different object from same table

I have a model X, that has two FK: A_id and B_id. These FK come from the same model, Y.

So, I was trying off how to get the data from the B_id object: I tried getting, but it doesn't existe. This is my initialize():

$this->belongsTo('A_id', 'Y', 'id');
$this->belongsTo('B_id', 'Y', 'id');

I need to declare other model with different name but with same class internal definition?



19.6k
Accepted
answer

I did to try it and yes, creating another model which source refers to the same as the first model works, so if anybody doesn't know a better workaround...



30.7k

Hi,

more "elegant" and more "usual" method is to use relationship aliasing:

// initialize method from "X" model
$this->belongsTo('A_id', 'Y', 'id',array("alias"=>"aRelation"));
$this->belongsTo('B_id', 'Y', 'id',array("alias"=>"bRelation"));

// use case, assuming that in your "Y" model you have a "name" field and that $X is an "X" model object:
$aName = $X->aRelation->name;
$bName = $X->bRelation->name;


19.6k

Thanks, that also works great!