php - Phalcon hasManyToMany stopped adding relation to database -
so first i've established 3 models , 3 tables hasmany relationship in 2 of them: user , group. usergroup belongto 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 ) )); } 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 create new user works:
public function createaction() { $this->checkpost(); // 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 $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 change relationship of user 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 added, relations - not.
help!
a many many relationships need table glue them together. in case usergroup. table not have relationship defined, helper other two.
that being said, must not use belongsto in usergroup, because declare many-to-one relationsship.
Comments
Post a Comment