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

Has 'hasManyToMany' model relationship behaviour changed?

We've just upgraded Phalcon to 3.1.1 from 2.0.13 and have found that the 'hasManyToMany' model relationships aren't working as they used to.

For example, our application allows accounts to have many users and users to have access to many accounts. So we have account and user tables, joined by an account_user table.

// In 'Account' model initialize()
$this->hasMany('id', 'AccountUser', 'account_id', array('alias' => 'AccountUsers'));

// In 'AccountUser' model initialize()
$this->hasOne('account_id', 'Account', 'id', array('alias' => 'Account'));

// In 'User' model initialize()
$this->hasManyToMany('id', 'Model\User\AccountUser', 'user_id', 'account_id', 'Model\User\Account', 'id', array('alias' => 'Accounts'));

Before the upgrade, this would return an array of multiple accounts:

$accounts = $this->user->Accounts;

However, it now only returns one account (not in an array) as it would if we had used the getFirst() method.

During the upgrade we've had to make changes to our model validation code, but haven't made any changes to how our relationships work. Is this a change in behaviour in the new Phalcon version, or are we missing something?

edited May '17

Well, tbh it should look like this:

In User and Account:

hasManyToMany and/or hasMany depending if you want to have actually related model or intermediate model

But in AccountUser as far as it know it should be correctly:

$this->belgonsTo('account_id', 'Account', 'id', array('alias' => 'Account'));

hasOnerelation is for example for:

user table:

id
firstName
account_id // with unique index

account table:

id
login

And then in User model you use:

$this->belongsTo('account_id', 'Account', 'id', ['alias' => 'account']); // this will allow you to acccess account of this user

In Account model:

$this->hasOne('id', 'User', 'account_id', ['alias' => 'user']); // this will allow you to access user which has this account

hasOne is pretty much the same stuff as hasMany, just instead of returning resultset it returns one model.