2

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)?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Theo
  • 87
  • 1
  • 10
  • if you found a solution, you should put it into an answer and mark it as the accepted one. You can self-answer a question, don't worry. – STT LCU May 05 '15 at 14:45

3 Answers3

1

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.

SigmaSteve
  • 664
  • 6
  • 25
1

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]);
    }
}
kero
  • 10,647
  • 5
  • 41
  • 51
  • 1
    @Theo great to hear. Maybe you can post it as an answer with a short explanation so anybody searching for this in the future easily finds it ;) – kero May 04 '15 at 00:48
0
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) )
Theo
  • 87
  • 1
  • 10