Laravel 以雄辩的方式更新数据透视表

Laravel 以雄辩的方式更新数据透视表,laravel,laravel-5,eloquent,pivot-table,Laravel,Laravel 5,Eloquent,Pivot Table,我在学生和机构联系人之间有一种多对多的关系 students应该只有两个institution\u contacts,并且我在透视表中有一个名为type的属性设置为1或2 因此,我的数据透视表如下所示: 机构联系人学生:id,机构联系人id,学生id,类型 我在决定如何处理添加/更新透视表的问题时遇到了困难。假设我有100名学生,我想给他们分配一个类型为1的联系人 我当前的解决方案是删除联系人,然后添加: $students = Student::all(); // the 100 studen

我在
学生
机构联系人
之间有一种多对多的关系

student
s应该只有两个
institution\u contact
s,并且我在透视表中有一个名为
type
的属性设置为1或2

因此,我的数据透视表如下所示:
机构联系人学生:id,机构联系人id,学生id,类型

我在决定如何处理添加/更新透视表的问题时遇到了困难。假设我有100名学生,我想给他们分配一个类型为1的联系人

我当前的解决方案是删除联系人,然后添加:

$students = Student::all(); // the 100 students
$contactId = InstitutionContact::first()->id; // the contact

foreach ($students as $student) {
    // remove existing contact
    $student
        ->institutionContacts()
        ->newPivotStatement()
        ->where('type', 1)
        ->delete();

    // add new contact
    $student
        ->institutionContacts()
        ->attach([$contactId => ['type' => 1]]);
}
然而,我认为这会对每个学生的数据库进行两次访问,对吗?因此,我是否最好为pivot表创建一个模型,删除与student id和type匹配的所有条目,然后简单地添加新条目?或者为数据透视表创建一个模型会被认为是一种糟糕的做法吗?有没有更好的方法来实现这一点,我错过了

请注意,我不使用sync的原因是因为我依赖type属性为每个学生只维护两个联系人。我不知道有什么方法可以修改现有的pivot,而不会对每个学生的两个联系人造成问题

编辑:

不用创建模型,我可以运行以下代码,使用
DB
执行删除

DB::table('institution_contact_student') // the pivot table
    ->whereIn('student_id', $studentIds)
    ->where('type', 1)
    ->delete();

如果我正确理解了您的问题,那么您可以使用updateExistingPivot方法更新您的pivot表。比如说,

public function institutionContacts(){
    return $this->belongsToMany('institutionContact')->withPivot('type');
}
在此之后,您只需使用以下代码:

$student
       ->institutionContacts()
       ->updateExistingPivot($contactId, ["type" => 1]);

希望这有帮助。

如果我正确理解了您的问题,那么您可以使用updateExistingPivot方法来更新您的pivot表。当然,首先您必须在关系中定义pivot。比如说,

public function institutionContacts(){
    return $this->belongsToMany('institutionContact')->withPivot('type');
}
在此之后,您只需使用以下代码:

$student
       ->institutionContacts()
       ->updateExistingPivot($contactId, ["type" => 1]);

希望这能有所帮助。

如果我有一个pivot模型,那么可以使用
一次性完成删除过程,其中
学生id
的删除过程可以一次完成,但是对于插入,您是对的,每个学生一个,但至少它被击倒了一半,对吗?如果我有一个pivot模型,删除过程可以使用
一次完成,其中
学生id
,但是对于插入,你是对的,每个学生一个,但至少它被击倒了一半,对吗?