[英]how to insert the pivot relationship in laravel
consider i have 2 models that have the pivot relationship many to many between them . 考虑我有2个模型,它们之间有很大的关系。 now when i want to insert the pivot table how can i achieve it currently i am doing this : 现在,当我想插入数据透视表时,我现在如何实现它:
DB::table('model1_model2')
->insert([
'something' => $something,
'something2' => $something2,
]);
and i kinda feel that its not right and i have do save it with some relation ship or sync !! 而且我有点觉得这是不正确的,我已经通过一些关系船或同步来保存了它! any idea how to do this ? 任何想法如何做到这一点? EDIT: Added relationship 编辑:添加关系
public function accommodationRoom()
{
return $this->belongsToMany(AccommodationRoom::class)->withPivot('guest_first_name','guest_last_name','guest_cell_phone','guest_nationality_id');
}
As mentioned in the Inserting & Updating Related Models - Many To Many Relationships documentation: 如“ 插入和更新相关模型 -多对多关系”文档中所述:
When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table: 将关系附加到模型时,您还可以传递要插入到中间表中的附加数据数组:
$model1->accommodationRoom()->attach($accommodationRoomId, [
'something' => $something,
'something2' => $something2,
]);
If you're attaching multiple relations then you would would pass a multidimensional array with the keys are the id
of the relation and the values are the arrays of additional data: 如果要附加多个关系,则将传递一个多维数组,其中键是该关系的id
,而值是其他数据的数组:
$model1->accommodationRoom()->attach( [
1 => ['something' => $something, 'something2' => $something2,],
3 => ['something' => 'something else', 'something2' => $something2,],
]);
The same is true for the sync()
method as well. sync()
方法也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.