2015-11-19 67 views
1

我有一個studentinstitution_contact之間的多對多關係。在Eloquent中更新數據透視表

student S的關係永遠只能有兩個institution_contact S和我有一個名爲type要設置的數據透視表的屬性爲1或2

所以,我的數據透視表看起來是這樣的: institution_contact_student: id, institution_contact_id, student_id, type

我在決定如何解決添加/更新數據透視表的問題時遇到了困難。比方說,我有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]]); 
} 

不過,我在想,這將會爲每個學生打兩次數據庫,對吧?那麼我最好爲數據透視表創建一個模型,並刪除與學生ID和類型相匹配的所有條目,然後添加新的條目?或者爲數據透視表創建一個模型被認爲是不好的做法,是否有更好的方法來完成這個我錯過了?

請注意我不使用同步的原因是因爲我依靠type屬性來維護每個學生只有兩個聯繫人。我不知道有什麼方法可以修改現有的數據透視表,而不會對每個學生需求的兩個聯繫人造成問題。

編輯:

而是創建一個模型,我可以運行下面的代碼來執行使用DB的刪除。

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

如果我有一個樞軸模型,可以一次性使用'whereIn'作爲'student_id'來完成刪除過程,但是對於插入,你是正確的,它將是每個學生一個,但至少它被擊倒一半權利? – haakym

回答

0

如果我理解正確的問題,那麼你可以使用updateExistingPivot方法來更新你的支點table.But第一當然你有你的關係定義軸心。例如,

public function institutionContacts(){ 
    return $this->belongsToMany('institutionContact')->withPivot('type'); 
} 

在此之後,所有你需要做的是使用下面的代碼:

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

希望這有助於。