我正在Laravel 5.4
上构建一个小应用程序并且在syncing
pivot table
many to many relationship
中遇到一点困难,我经历了this link并且没有正确理解,
我有一个必填字段的透视表(我的意思是它有字段)。我有这样的关系:
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 :(得分:2)
我做了类似的事情:
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);
它有效。所以基本上想法是使用pivot元素的键来推送一个数组,它将正确执行。