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