Reputation: 107
I need to add a ROLE relation to a USER.
So I did the following:
$user->add('roles', $roles_ids_array );
It works, but the system tries to add it without checking if the relation ALREADY EXISTS in the DB, giving me a mysql "Duplicate entry" error.
In Kohana 2.x it works perfectly (the system does the auto check). Is there an easy to do this in KO3.3?
How can I do that without using $user->has(etc)
?
Upvotes: 2
Views: 119
Reputation: 107
As kohana does not check for previous relations,
we must tell it wich ids to remove/add doing this:
// two arrays: existing ids array and new ids array
// with these lines you'll get what you need, rather than doing foreach,etc
// array_diff is a php function
$ids_remove = array_diff($array1 ,$array2);
$ids_add = array_diff($array2 ,$array1);
// now simply execute kohana's native functions to add/remove many-to-many relations
$obj->remove('relation',$ids_remove) )
$obj->add('relation',$ids_add) )
Upvotes: 0
Reputation: 10638
You could get all roles via $user->roles->find_all()
and iterate over them, deleting the duplicates via array_search()
and unset()
like this
foreach ($user->roles->find_all() as $role) {
if (($key = array_search($role->id, $roles_ids_array)) !== FALSE) {
unset($roles_ids_array[$key]);
}
}
Upvotes: 1
Reputation: 684
According to the documentation, Kohana 3 doesn't check that the existing relationship exists before adding the new one. So it is behaving as intended, but I understand that this doesn't solve your problem.
The most efficient way to do it would be to use a DB::select on the pivot table, then wrap the add() in an if statement where the select has returned 0 rows.
Hope this helps.
Upvotes: 1