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

Fetching records from Many to Many relationship does not work as expected in Phalcon.

Here is the tables.

CREATE TABLE IF NOT EXISTS tt_users ( id int(11) NOT NULL AUTO_INCREMENT, email varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=21 ;

CREATE TABLE IF NOT EXISTS tt_groups ( id int(11) NOT NULL AUTO_INCREMENT, title varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, user_id int(11) DEFAULT NULL,

PRIMARY KEY (id), KEY title (title), KEY user_id (user_id),

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=17 ;

CREATE TABLE IF NOT EXISTS tt_group_members ( id int(11) NOT NULL AUTO_INCREMENT, group_id int(11) DEFAULT NULL, user_id int(11) DEFAULT NULL,

PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=8 ;

Here are models:

  1. Users model

    public function getSource() { return 'tt_users'; } /**

    • Initialize relationship */ public function initialize(){

      $this->hasManyToMany("id", "GroupsMembers", "user_id","group_id", "Groups", "id", array('alias' => 'GroupsMembers') );

    }

  2. Group model

    public function getSource() { return 'uo_groups'; }

    /**

    • Initialize relationship */ public function initialize(){

      $this->hasManyToMany("id", "GroupsMembers", "group_id","user_id", "Users", "id", array('alias' => 'Users') );

    }

  3. Groups Members models, this table relate group and users.

    public function getSource() { return 'uo_group_members'; }

    /**

    • Initialize relationship */ public function initialize(){

      $this->belongsTo("group_id", "Groups", "id", array('alias' => 'Group')); $this->belongsTo("user_id", "Users", "id", array('alias' => 'User'));

    }

Below is the code from UserController where I need to list all subscribed groups for a user.

$user = Users::find('id = '.$user_id);

$subscribed_groups = $user->groupsMembers;

foreach($groupMembers as $groupMember){
    echo $groupMember->groups->title;
}

I receive following error:

Notice: Undefined property: Phalcon\Mvc\Model\Resultset\Simple::$GroupsMembers in /var/www/html/uno/apps/webservice/controllers/UserController.php on line 245

Right now I am using PHQL as alternate option but I expected to get results by relationship. Apperciate if someone help me to identify the issue.

Thanks.



51.1k
Accepted
answer
$users = Users::find(['id = :user_id:', 'bind' => ['user_id' => $user_id]]);

foreach ($users as $user) {
  $subscribed_groups = $user->groupsMembers;

  foreach($groupMembers as $groupMember){
      echo $groupMember->groups->title;
  }
}

OR

$user = Users::findFirstById($user_id);

$subscribed_groups = $user->groupsMembers;

foreach($groupMembers as $groupMember){
    echo $groupMember->groups->title;
}

find() method is returning an instance of Phalcon\Mvc\Model\Resultset\Simple but findFirst() will return an instance of your object (User in your case)

Thank you Calin.

It gives me another error but I beleive it is becuse of my setup. My models does not autoloading, so I had to include the every model on my controller calss, like I had include models on my UserController:

namespace Uno\Webservice\Controllers; use Uno\Webservice\Models\Users; use Uno\Webservice\Models\Groups; use Uno\Webservice\Models\GroupsMembers;

The error I am getting is:

Fatal error: Uncaught exception 'Phalcon\Mvc\Model\Exception' with message 'Model 'Groups' could not be loaded' in /var/www/html/uno/apps/webservice/controllers/UserController.php:245 Stack trace: #0 [internal function]: Phalcon\Mvc\Model\Manager->load('Groups') #1 [internal function]: Phalcon\Mvc\Model\Query->_prepareSelect() #2 [internal function]: Phalcon\Mvc\Model\Query->parse() #3 [internal function]: Phalcon\Mvc\Model\Query->execute() #4 [internal function]: Phalcon\Mvc\Model\Manager->getRelationRecords(Object(Phalcon\Mvc\Model\Relation), NULL, Object(Uno\Webservice\Models\Users), NULL) #5 /var/www/html/uno/apps/webservice/controllers/UserController.php(245): Phalcon\Mvc\Model->__get('groupsMembers') #6 [internal function]: Uno\Webservice\Controllers\UserController->followedGroupsAction() #7 [internal function]: Phalcon\Dispatcher->dispatch() #8 /var/www/html/uno/public/index.php(179): Phalcon\Mvc\Application->handle() #9 /var/www/html/uno/public/index.php(185): Application->main() #10 {main} thrown in /var/www/html/uno/apps/webservice/controllers/UserController.php on line 245

I have following code in Module.php and thought I do not have to include the model in controller, but it seems it does not autoload the model.

<pre> public function registerAutoloaders() {

    $loader = new Loader();

    $loader->registerNamespaces(array(
        'Uno\Webservice\Controllers' => __DIR__.'/controllers/',
        'Uno\Webservice\Models' => __DIR__.'/models/',

    ));

    $loader->registerDirs(array(
        __DIR__.'/controllers/',
        __DIR__.'/models/',

    ));

    $loader->register();
}

</pre>

Apperciate if you can help me in that.

Thanks.