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

Many-to-many problem

Hi again, I have simple relation (typical tree):

        $this->hasManyToMany(
            "id",
            "App\Model\UserRoleHasParentUserRole",
            "user_role_id",
            "parent_user_role_id",
            "App\Model\UserRole",
            "id",
            array(  'alias' => 'parentRoles')
        );

When I want to show, it works:

$r = UserRole::findFirst();
dump($r->parentRoles);

But saving not:

        $new = [];
        $new[] = UserRole::find(['id' => 4]);
        $r->parentRoles = $new;
        $r->save();

I can't even set "parentRoles" property value. Do I need reflection?

parentRole is a magic method, provided by Phalcon based on your naming scheme.

If you want to save the object with ORM, you will have to recreate the layout of the data (2 dimensions, instead of your 1 dimension):

$new = [];
$role2role = new UserRoleHasParentUserRole();;
$role2role->assign(['some'=>'data'])
$new[] = $role2role;
$r->parentRoles = $new;
$r->save();

They key is that parentRoles is a table reference to App\Model\UserRoleHasParentUserRole, not App\Model\UserRole.



8.3k

It works only when I save join table:

        $role2role->save();

I found solution seems better:

    public function setParentUserRoles($array) {

        $this->__set("parentUserRoles", $array);
    }

But even above merging data instead replace it. It seems I have to implement add, remove, clean and set manually - but I consider doctrine as my ORM. And another problem occurs, all fresh saved records are duplicated - it could be solved by adding unique index onto join table.

edited Jan '18

Doctrine is much, much, much slower than phalcon orm. Yea, many to many is really badly supported in phalcon. Just best is to save/create/delete related records yourself.



8.3k

Doctrine is much, much, much slower than phalcon orm

Like everything what provides some functionality in compare with blank class :) There is no point to compare performance if tools don't provide similar functionality. Furthermore, it usual turns out, that writing all missing functions by own leads app to performance collapse. I really want apreciate Phalcon performace, but it has to work first. Performance without functionality is useless for me.