Tutorial :Kohana “has many through” relation


I was wondering what the best method is to edit a 'has many through' relation with a form. Let's say I have a bunch of users that can belong to multiple categories.

The form would have some checkboxes like this:

<input type="checkbox" name="category_ids" value="1" />      <input type="checkbox" name="category_ids" value="2" />  

Then in my controller I could do something like:

// dump all relations  DB::delete('users_categories')->where('user_id','=',$user->id)->execute();    // add new relations  foreach (explode(',', $_POST['category_ids']) as $category)      $user->add('category', ORM::factory('category', $category))  

But this looks too complicated to me (also because I have more than one 'has many through' relations). Is there an easier / better way to accomplish this using kohana orm? :)


thats how i do it

// C  $roles = ORM::factory('role')->find_all();  foreach ($roles as $role)  {      $action = isset($form['user']['roles'][$role->id]) ? 'add' : 'remove';        // you dont need this if-statement if you'r using ko2      if ($action === 'add' && $user->has('roles', $role))      {          continue;      }        $user->$action('roles', $role);  }    // V  <?  $roles = ORM::factory('role')->find_all();  foreach ($roles as $role):  ?>      <?= form::checkbox('user[roles]['.$role->id.']', $role->id, $user->has('roles', $role)) ?>      <?= form::label('user_roles_'.$role->id, $role->name) ?>      <br />  <? endforeach ?>  


To find what was added (reverse the args to find what was removed) consider using array_diff().

With this you should be able to code something more efficient than pure orm.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »