0
我在Laravel 5.4
建立一個小的應用程序,並在syncing
的pivot table
在many 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);
}
指導我做到這一點。由於
不是$ pivotData你想傳遞給sync()嗎? – btl
@btl是的,我想出一個方法來將'$ pivotData'傳入同步 –
您看起來很近,使用$ 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