views:

127

answers:

2

Hi,

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

A: 

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 ?>
antpaw
But this is not really efficient either, isn't it? If you have, for example, 20 options and only 1 checked, kohana will execute 19 delete statements.
acidtv
well youve asked for simplicity. efficiency is not really the goal of orm, especially in the form submit logic. but since you know whether the user has the role you can add another if-continue statement if the user doesnt have the role and the action === 'remove'
antpaw
A: 

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.

Lethargy