2017-06-15 59 views
0

我在Laravel 5.4建立一個小的應用程序,並在syncingpivot tablemany to many relationship面臨一個難度不大的屬性,我通過this link去了,沒有正確的理解,同步與支點的陣列Laravel

我有一個數據透視表是必填字段(我的意思是它將有字段)。我有這樣的關係:

class Interaction extends Model 
{ 

    public function clientsAssociation() 
    { 
     return $this->belongsToMany('App\Contact', 'contact_client_interaction', 'interaction_id', 'contact_id')->withPivot('company_id')->withTimestamps(); 
    } 

} 

我得到一組數組與同步到這些模型相關的值。我很困惑如何放置數據透視數據,同時更新:

foreach ($data['clientParticipants'] as $clientParticipant) 
{ 
    if(array_key_exists('company_id', $clientParticipant)) 
    { 
     $contact[] = Contact::find(json_encode($clientParticipant['value'])); 
     $pivotData = ['company_id' => $clientParticipant['company_id']]; 
    } 
    else 
    { 
     $contact[] = Contact::find(json_encode($clientParticipant['value'])); 
     $pivotData = ['company_id' => Contact::find(json_encode($clientParticipant['value']))->company()->withPivot('created_at')->orderBy('pivot_created_at', 'desc')->first()->id])]; 
    } 

    $interaction->clientsAssociation()->sync($contact); 
} 

指導我做到這一點。由於

+0

不是$ pivotData你想傳遞給sync()嗎? – btl

+0

@btl是的,我想出一個方法來將'$ pivotData'傳入同步 –

+0

您看起來很近,使用$ clientParticipant ['company_id']作爲$ clientData的鍵並將其推送到數組上。然後您可以同時同步所有數據。請參閱此處的答案:https://stackoverflow.com/questions/27230672/laravel-sync-how-to-sync-an-array-and-also-pass-additional-pivot-fields?noredirect=1&lq=1 – btl

回答

0

嗯,我做了這樣的事情:

foreach ($data['clientParticipants'] as $clientParticipant) 
{ 
    if(array_key_exists('company_id', $clientParticipant)) 
    { 
     $pivotData = ['company_id' => $clientParticipant['company_id']]; 
     $syncData = Contact::find(json_encode($clientParticipant['value']))->id; 
     $contact[$syncData] = $pivotData; 
    } 
    else 
    { 
     $value = Contact::find(json_encode($clientParticipant['value'])); 
     $syncData = $value->id; 
     $pivotData = ['company_id' => $value->company()->withPivot('created_at')->orderBy('pivot_created_at', 'desc')->first()->id]; 
     $contact[$syncData] = $pivotData; 
    } 
} 
$interaction->clientsAssociation()->sync($contact); 

和它的作品。所以基本上的想法是推動一個數組與樞軸元素的關鍵,它會正確執行。