Phalcon hasManyToMany已停止添加与数据库的关系

时间:2014-03-24 23:45:01

标签: php mysql many-to-many foreign-key-relationship phalcon

首先,我在其中2个中建立了3个模型和3个具有hasMany关系的表:User和Group。 UserGroup属于User和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
        )
    ));
}

组:

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" => "Группа не может быть удалена, потому что её используют некоторые пользователи"
        )
    ));
}

用户组:

<?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" => "Выбранная группа для пользователя не существует!"
        )
    ));
}
}

然后,当我创建一个新用户时,一切正常:

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;
    }
}

但是当我改变User与n-n的关系时:

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

它停止了工作。没有错误。用户被添加,关系 - 而不是。

帮助!

1 个答案:

答案 0 :(得分:2)

多对多关系需要另一个表将它们粘合在一起。在您的情况下,这是UserGroup。该表没有定义任何关系,它只是其他两个的帮手。

话虽如此,你不能在UserGroup中使用belongsTo,因为这会声明多对一的关系。