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

How save existed models as manymany

Hi Guys! I have a some problem with saving existed models as manytomany relations. If i create new, all fine.

$groups = [];
$groups[0] = new UserGroups;
$groups[0]->name = 'test2';
$groups[0]->active = 1;
$user = new static;
$user->assign($data);
$user->groups = $groups;

$user->create();

but if i set existed

$groups = UserGroups::find([1])->toArray();
$user = new static;
$user->assign($data);
$user->groups = $groups;

$user->create();

I get error Record cannot be created because it already exists

If i change create to save, user with id=1 is updated.

If set groups as ResultSet, nothing added in relations table, but new user is created

$groups = UserGroups::find([1]);
$user = new static;
$user->assign($data);
$user->groups = $groups;
$user->create();


8.0k

Relations defined as

UserGroupsRel

<?php

namespace Phalcon\UserPlugin\Models\User;

class UserGroupsRel extends \Phalcon\UserPlugin\Models\User\Generated\UserGroupsRel
{

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        $this->belongsTo('user_id', 'Phalcon\UserPlugin\Models\User\User', 'id', ['alias' => 'user']);
        $this->belongsTo('group_id', 'Phalcon\UserPlugin\Models\User\UserGroups', 'id', ['alias' => 'group']);
    }
}

User

<?php

namespace Phalcon\UserPlugin\Models\User;

use Phalcon\Mvc\Model\Validator\Email as Email;
use Phalcon\Mvc\Model\Validator\Uniqueness;

class User extends \Phalcon\UserPlugin\Models\User\Generated\User
{
     public function initialize()
    {
        $this->hasManyToMany(
                "id", "Phalcon\UserPlugin\Models\User\UserGroupsRel", "user_id", "group_id", "Phalcon\UserPlugin\Models\User\UserGroups", "id"
                , ['alias' => 'groups']
        );
    }
}

UserGroups

<?php
namespace Phalcon\UserPlugin\Models\User;

class UserGroups extends \Phalcon\UserPlugin\Models\User\Generated\UserGroups
{
    public function initialize()
    {
        $this->hasManyToMany(
                "id", "Phalcon\UserPlugin\Models\User\UserGroupsRel", "group_id", "user_id", "Phalcon\UserPlugin\Models\User\User", "id"
                , ['alias' => 'users']
        );
    }
}


1.4k

Hi, it seems that we should create a new array :

$groups = UserGroups::find([1])->toArray();
$user = new static;
$user->assign($data);

$nGroups=array();
foreach ($groups as $g){
    $nGroups[]=$g;
}
$user->groups=$nGroups;
$user->create();