We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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?



33.8k
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...



43.9k

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;


33.8k

Thanks, that also works great!