如何在laravel中插入枢轴关系

时间:2019-07-17 11:04:03

标签: php laravel api

考虑一下,我有2个模型,它们之间的枢纽关系是多对多的。现在,当我想插入数据透视表时,我现在如何实现它:

DB::table('model1_model2')
            ->insert([
                'something' => $something,
                'something2' => $something2,
            ]);

我有点觉得这是不对的,我已经通过一些关系运送或同步来保存了它!任何想法如何做到这一点? 编辑: 新增关系

 public function accommodationRoom()
    {
        return $this->belongsToMany(AccommodationRoom::class)->withPivot('guest_first_name','guest_last_name','guest_cell_phone','guest_nationality_id');
    }

1 个答案:

答案 0 :(得分:1)

Inserting & Updating Related Models - Many To Many Relationships文档中所述:

  

将关系附加到模型时,您还可以传递要插入到中间表中的附加数据数组:

$model1->accommodationRoom()->attach($accommodationRoomId, [
    'something'  => $something,
    'something2' => $something2,
]);

如果要附加多个关系,则将传递一个多维数组,其键为该关系的id,其值是附加数据的数组:

$model1->accommodationRoom()->attach( [
    1 => ['something'  => $something, 'something2' => $something2,],
    3 => ['something'  => 'something else', 'something2' => $something2,],
]);

sync()方法也是如此。