Laravel,sync() - 如何同步数组,并传递其他枢轴字段? [英] Laravel, sync() - how to sync an array and also pass additional pivot fields?
本文介绍了Laravel,sync() - 如何同步数组,并传递其他枢轴字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
官方Laravel文档在 sync()
功能:
Official Laravel documentation has this on sync()
function:
$user->roles()->sync( array( 1, 2, 3 ) );
您还可以将其他数据透视表值与给定的ID相关联:
You may also associate other pivot table values with the given IDs:
$user->roles()->sync( array( 1 => array( 'expires' => true ) ) );
在后一个示例中,只添加了一个枢轴列。我不明白的是,如果有多个行要同步,那么如何关联其他数据透视表记录?
In the latter example only a single pivot row is being added. What I don't understand is how can I associate other pivot table records if there are more than one rows to be synced?
提前感谢
推荐答案
为了同步
多个模型以及自定义数据透视数据,您需要: / p>
In order to sync
multiple models along with custom pivot data, you need this:
$user->roles()->sync( array(
1 => array( 'expires' => true ),
2 => array( 'expires' => false ),
...
));
sync( array(
related_id => array( 'pivot_field' => value ),
...
));
编辑
edit
回答评论:
$speakers = (array) Input::get('speakers'); // related ids
$pivotData = array_fill(0, count($speakers), ['is_speaker' => true]);
$syncData = array_combine($speakers, $pivotData);
$user->roles()->sync($syncData);
这篇关于Laravel,sync() - 如何同步数组,并传递其他枢轴字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文