简体   繁体   中英

sync an array with pivot attributes in Laravel

I'm building a small application on Laravel 5.4 and facing a little difficulty in syncing the pivot table in many to many relationship , I went through this link and not understood properly,

I'm having a pivot table which is mandatory field(I mean it will have field). I'm having a relationship something like this:

class Interaction extends Model
{

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

}

I'm getting an array with set of values related to sync to these models. I'm confused how to place pivot data and while updating:

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

Guide me to achieve this. Thanks

Well I did something like this:

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

And it works. So basically idea is to push an array with key of pivot elements and it will execute properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM