phpkohanakohana-ormkohana-3.3

Add relationship, handling duplicating entries - KOHANA 3.3


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


Solution

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