如何使用枢轴值同步多对多?

How to sync many to many with a pivot value?

class User extends \Eloquent {
 public function cards() {
       return $this->belongsToMany('Card','user_card')->withPivot('sort')->orderBy('user_card.order', 'asc');
    }

}

我可以通过 $user->sync(Input::get("card_ids",[])) 附上卡片,但是我正在碰壁试图弄清楚如何将枢轴值 "sort" 更新为 array_keys(Input::get("card_ids",[])) 的值 [基本上命令用户在]

中提交它们

eloquent可以吗?

同步数据透视列的语法是这样的:

$user->roles()->sync(array(1 => array('expires' => true)));

要实现这一点,您可以先使用 array_flip 将键与值切换,然后 array_map 将值转换为所需格式:

$cards = Input::get('card_ids', []);
$cards = array_flip($cards);
$cards = array_map(function($sort){
    return array('sort' => $sort);
}, $cards);
$user->cards()->sync($cards);