Hi, I have a similar question.
I have 2 tables: Users
and Friends
.
/**
* Main Users Model
*/
namespace Models\Users;
class Main extends \Models\Main
{
public function initialize()
{
$this->hasManyToMany(
'id',
'Models\Users\Friends',
'user_id',
'friend_id',
'Models\Users\Main',
'id', array('alias' => 'friends')
);
}
}
And
/**
* User's friends Model
*/
namespace Models\Users;
class Friends extends \Models\Main
{
}
Users
is the main table that contains all users and their data. Friends
is just a relations table with 2 columns: user_id and friend_id, both uses main Users
table. As you see in Users
I'm using hasManyToMany relationship. It works perfect while reading:
$user = \Models\Users\Main::findFirst(1);
foreach($user->friends as $friend)
{
echo $friend->name;
}
But I can't understand how to add new friends for users. I'm trying to update:
$new_friends = array();
$user = \Models\Users\Main::findFirst(1);
$new_friends[] = \Models\Users\Main::findFirst(2);
$new_friends[] = \Models\Users\Main::findFirst(3);
$user->friends = $new_friends;
$user->save();
And this code is just adding/overwriting (expectedly) a single row:
+---------+-----------+
| user_id | friend_id |
+---------+-----------+
| 1 | 3 |
+---------+-----------+
On saving it's trying to add already existing user:
$new_friends = array();
$user = new \Models\Users\Main();
$user->name = 'New user';
$new_friends[] = \Models\Users\Main::findFirst(2);
$new_friends[] = \Models\Users\Main::findFirst(3);
$user->friends = $new_friends;
$user->save();
/**
* Integrity constraint violation: 1062 Duplicate entry 'User with id 2' for key
*/
Is it possible to solve this task without third table and additional ids? I've barely used Kohana ORM before, so the solution may be obviously for the community.
Thanks in advance!