Pregunta

So first I've established 3 models and 3 tables with hasMany relationship in 2 of them: User and Group. UserGroup is belongTo User and Group.

class User extends \Phalcon\Mvc\Model {

public $id;
public $name;

public function initialize()
{
    $this->hasMany(
        'id',
        'UserGroup',
        'user_id',
        array(
        'foreignKey' => array(
            'action' => Relation::ACTION_CASCADE
        )
    ));
}

Group:

use Phalcon\Mvc\Model\Validator\PresenceOf;

class Group extends \Phalcon\Mvc\Model {

public $id;
public $name;

public function initialize()
{
    $this->hasMany('id', 'UserGroup', 'group_id', array(
        "foreignKey" => array(
            "message" => "Группа не может быть удалена, потому что её используют некоторые пользователи"
        )
    ));
}

UserGroup:

<?php
class UserGroup extends \Phalcon\Mvc\Model {

public $id;
public $group_id;
public $user_id;

public function initialize()
{
    $this->belongsTo("user_id", "User", "id", array(
        "foreignKey" => true
    ));

    $this->belongsTo("group_id", "Group", "id", array(
        "foreignKey" => array(
            "message" => "Выбранная группа для пользователя не существует!"
        )
    ));
}
}

Then, when I create a new user It all works:

public function createAction()
{
    $this->checkPost();

    // Get user name
    $userName = $this->request->getPost('name');
    $userGroups = $this->request->getPost('groups');

    if ($this->checkExisting($userName)) {
        $this->returnJson('error', 'Такой пользователь уже существует!');
        return;
    }

    // Create user
    $user = new User();

    $user->name = $userName;
    $success = $user->create();

    if ($success) {

        // Add user groups
        $userGroupModels = array();
        $userGroupCount = 0;
        if (!empty($userGroups)) {
            foreach($userGroups as $groupId) {
                $userGroupModels[ $userGroupCount ] = new UserGroup();
                $userGroupModels[ $userGroupCount ]->user_id = $user->id;
                $userGroupModels[ $userGroupCount ]->group_id = $groupId;

                $userGroupCount++;
            }

            $user->userGroup = $userGroupModels;
            $user->save();
        }

        $this->returnJson('success', 'Пользователь добавлен!');
        return;
    } else {
        $this->returnJson('error', 'Ошибка добавления пользователя!');
        return;
    }
}

But when I change relationship of User to n-n:

$this->hasManyToMany(
        'id',
        'UserGroup',
        'user_id', 'group_id',
        'Group',
        'id',
        array(
        'foreignKey' => array(
            'action' => Relation::ACTION_CASCADE
        )
    ));

It stopped working. No errors. User is added, relations - not.

Help!

¿Fue útil?

Solución

A many to many relationships need another table to glue them together. In your case this is UserGroup. That table does not have any relationship defined, it is just a helper for the other two.

That being said, you must not use belongsTo in UserGroup, because this would declare a many-to-one relationsship.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top