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

Get many to many relationship between two models

Hi

I try to retreive a many to many relation between 2 models, for I use the model function getRelationsBetween and pass the 2 models name in parameters but a var_dump return me false.

How I have to use this function? An other ways to achieve this?



43.9k

Hi,

So far as I know, there is no getRelationsBetween method in the Phalcon\Mvc\Model class (https://docs.phalcon.io/en/3.3/api/Phalcon_Mvc_Model)

to use relationships with phalcon's ORM, you'll have to declare the explicitly in the model class: https://docs.phalcon.io/en/3.3/db-models-relationships#defining

then you can easily use them as explained in the doc: https://docs.phalcon.io/en/3.3/db-models-relationships#taking-advantage-of

happy coding ;-)



3.3k

Hi le51

Sorry the getRelationsBetween is function of Model\Manager https://docs.phalcon.io/en/3.2/api/Phalcon_Mvc_Model_Manager



43.9k

Ok. For better help, show us:

  • your models classes
  • the way you use them with getRelationsBetween


3.3k
edited Apr '18

My 3 Models

class Users extends Model {

 public function initialize() {
        $this->hasManyToMany('id', __NAMESPACE__ . '\UsersRoles', 'userid', 'roleid', __NAMESPACE__ . '\Roles', 'id', array("alias" => "Roles"));
        }
}
class Roles extends Model {

 public function initialize() {
        $this->hasManyToMany('id', __NAMESPACE__ . '\UsersRoles', 'roleid', 'userid', __NAMESPACE__ . '\Users', 'id', array("alias" => "Users"));
        }
}
class UsersRoles extends Model {

 public function initialize() {
        $this->belongsTo("userid", __NAMESPACE__ . "\Users", "id", ["alias" => "user"]);
        $this->belongsTo("roleid", __NAMESPACE__ . "\Roles", "id", ["alias" => "role"]);
        }
}

the use of getRelationsBetween in controller

$modelUsers = __NAMESPACE__."\Users";
$modelRoles = __NAMESPACE__."\Roles";
$this->modelsManager->initialize(new $modelUsers());
$rel = $this->modelsManager->getRelationsBetween($modelUsers, $modelsRoles);

What are you trying to accomplish? Why are you trying to get the relationship itself?



3.3k

In the user form I display a table of the user roles and a button to add role to user.

When I click on this button I display a modal with list of roles that are not linked to the user.

I choose the role that I want to add and click on a button that perform the UsersRoles records creation.

I want to build this widget (table + modal) to be generic, today I need display UsersRoles tomorrow Posts, Transactions, whatever ...

I managed to achieve this using getRelationByAlias but I think using getRelationsBetween is more elegant and generic.



43.9k

Hi,

I think it's more like you've initialized a new Model, but "as is", it does not hold any relation ... so var_dump($rel); return null (or something like this ;-))

otherwise model declarations looks correct.