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

Saving hasManyToMany not saving related objects

Can not figure out what I'm doing wrong, please help :)

Controller:

    $pg = new \Models\PermissionGroup;
    $pg->name = 'Owner';

    $p = [];

    $p[0] = new \Models\Permission;
    $p[0]->name = 'Perm1';

    $p[1] = new \Models\Permission;
    $p[1]->name = 'Perm2';

    $pg->Permissions = $p;
    $pg->save();

Models:

class PermissionGroup extends \Phalcon\Mvc\Model
{
  public function initialize()
  {
      $this->hasMany(
          "permission_group_id",
          "\Models\PermissionGroupPermission",
          "permission_group_id"
          );

      $this->hasManyToMany(
          "permission_group_id",
          "\Models\PermissionGroupPermission",
          "permission_group_id", "permission_id",
          "\Models\Permission",
          "permission_id"
      );
  }
public $permission_group_id;
public $name;
}

class Permission extends \Phalcon\Mvc\Model
{
  public function initialize()
  {
      $this->hasMany(
          "permission_id",
          "\Models\PermissionGroupPermission",
          "permission_id"
          );

} public $permission_id; public $name; }

class PermissionGroupPermission extends \Phalcon\Mvc\Model
{
  public function initialize()
  {
      $this->belongsTo(
          "permission_group_id",
          "\Models\PermissionGroup",
          "permission_group_id"
      );
      $this->belongsTo(
          "permission_id",
          "\Models\Permission",
          "permission_id"
      );
  }
  public $permission_group_permission_id;
  public $permission_group_id;
  public $permission_id;
}

The result of the $pg->save(); is only the permission_group table is populated.


1.3k
Accepted
answer

Found the solution, just requires a hasManyToMany in parent class