将数组与 Laravel 中的数据透视属性同步

sync an array with pivot attributes in Laravel

我正在 Laravel 5.4 上构建一个小应用程序,在 syncingmany to many relationship 中的 pivot table 中遇到了一些困难,我经历了 this link并且理解不正确,

我有一个主元table,它是必填字段(我的意思是它会有字段)。我有这样的关系:

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);
}

指导我实现这一目标。谢谢

好吧,我做了这样的事情:

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 元素的键推送一个数组,它会正确执行。