2017-03-04 40 views
2

我有兩個模型之間的多對多關係:旅遊和地點,我有一些額外的樞軸表字段(每個位置停留的日夜)。
一切都設置和工作得很好。Laravel多對多,附加一個模型,多次

每個巡迴賽可以有多個位置,該點是,每天遊可以有相同的位置,多次:

---------------------------------------------------- 
| tour_id | location_id | days | nights | ordering | 
---------------------------------------------------- 
| 1 |  1  | 4 | 3 |  1 | 
---------------------------------------------------- 
| 1 |  2  | 5 | 5 |  2 | 
---------------------------------------------------- 
| 1 |  1  | 2 | 1 |  3 | 
---------------------------------------------------- 

因此,我們有:

foreach ($locations as $location) { 
    $tour->locations()->attach($location->id, [ 
     'days' => $location->days, 
     'nights' => $location->nights, 
     'ordering' => $location->ordering 
    ]); 
} 

這將導致只增加2行到數據透視表。 我們如何才能將單個地點附加到一次旅遊,多次?

問候,

回答

1

在你的循環要連接的模式,因而只會增加一個關係。如果需要額外的關係,您將不得不手動添加。

該循環一次添加全部3個。現在你想添加第四個位置?

$location4 = Location::find(4); 

$tour->locations()->attach($location4, [ 
    'days' => $location4->days, 
    'nights' => $location4->nights, 
    'ordering' => $location4->ordering 
]); 

爲了避免替換,使用syncWithoutDetaching()

$tour->locations()->syncWithoutDetaching($location4, [ 
    'days' => $location4->days, 
    'nights' => $location4->nights, 
    'ordering' => $location4->ordering 
]); 
+0

$位置包含所有3組數據:'[{ 「ID」: 「1」, 「天」: 「4」, 「夜」 :「3」,「orders」:「1」},{「id」:「2」,「days」:「5」,「nights」:「5」,「ordering」:「2」},{「 id「:」1「,」days「:」2「,」nights「:」1「,」ordered「:」3「}]''所以我們最終將所有3都連接起來,但是它以某種方式覆蓋了第一個位置與第三個。 – MeeDNite

+0

嘗試使用我的更新。 'syncWithoutDetaching()' – EddyTheDove

+0

位置是動態的並且來自請求。我沒有辦法像這樣分開他們。也許在原始循環中使用'syncWithoutDetaching'? – MeeDNite