2010-08-03 68 views
1

我想知道什麼最好的方法是編輯一個'有很多通過'關係的形式。 假設我有一羣可以屬於多個類別的用戶。Kohana「有很多通過」關係

形式會有些複選框這樣的:

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

然後在我的控制,我可以這樣做:

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

但是,這看起來太複雜,我(還因爲我有更多的比'有很多通'關係)。有沒有更容易/更好的方式來完成這個使用kohana orm? :)

+0

你沒有關閉「explode()」 – Kemo 2010-08-03 12:57:50

+0

你是對的。刪除也沒有工作,現在修復。 – acidtv 2010-08-03 13:22:45

回答

0

這就是我怎麼辦呢

// 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 ?> 
+0

但是這也不是很有效,不是嗎?例如,如果您有20個選項,並且只有1個選中,kohana將執行19條刪除語句。 – acidtv 2010-08-04 07:49:15

+0

以及你問過簡單。效率並不是真正的目標,特別是在表單提交邏輯。但既然你知道用戶是否有角色,如果用戶沒有角色和動作,你可以添加另一個if-continue語句==='remove' – antpaw 2010-08-04 09:04:09

0

要查找添加什麼(扭轉參數傳遞給找到輾轉什麼)考慮使用和array_diff()。

有了這個,你應該能夠編寫比純粹orm更高效的東西。