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

Relation 1 or 0 in Model

Hey.. I try to create a relation between two Models (Card and User):

  • Card can have one or no user.
  • User can have one or many cards.

in user, i have this relationsip:

$this->hasMany('id', 'Card', 'user_id', array('alias' => 'cards'));

Which works.

Now, i should use $this->belongsTo('user_id', 'User', 'id', array('alias' => 'user')); in order to have the relation to the user. It works if the card has a user, but if i generate a card, the user will be null and it fails.

How can i solve this?



12.2k

Hi, you can try this

$this->belongsTo('user_id', 'APP\Models\Users', 'id', array('reusable' => true, 'alias' => 'user'));