0

I have two models as follows,

User {
    public function param()
    {
        return $this->belongsToMany(
            Models\Param::class, 'param_user_map', 'user_id', 'param_id')
                ->withPivot('experience', 'param_extra');
    }
}

Params {
    public function user()
    {
        return $this->belongsToMany(
            Models\User::class, 'param_user_map', 'param_id', 'user_id')
                ->withPivot('experience', 'param_extra');
    }
}

And my mapping table,

param_user_map
  -param_id
  -user_id
  -experience
  -param_extra

And data which I am working on is like,

user_id  param_id  experience  param_extra
51       2         3           param2_1
51       2         3           param2_2
51       3         3           param3_2

When I use Eloquent to sync this data only one of the first two is saved.

Is there any way I can sync data with [param_id,user_id,param_extra] as unique combination.

I tried with,

$table->unique(['param_id','user_id','param_extra']);

and

foreach ($data['param_collection'] as $param) {
    $params = [
        'experience' => $params['experience'],
        'param_extra' => $params['param_extra'],
    ];
    $user->param()->sync([$param['param_id'] => $params]);
}

Didn't work.

Any solution ?

alepeino
  • 9,551
  • 3
  • 28
  • 48
sudhirk496
  • 74
  • 3

1 Answers1

0

I think you can't do what you want with sync. If you want to do more than just creating unique "User"-"Param" pairs with no extra attributes, you can use attach:

foreach ($data['param_collection'] as $param) {
    $user->param()->detach(); //if you want to clear previous params

    $user->param()->attach($param['param_id'], [
        'experience' => $param['experience'],
        'param_extra' => $param['param_extra']
    ]);
}
alepeino
  • 9,551
  • 3
  • 28
  • 48
  • I am already doing it with detach() and attach(), was wondering if there is a way to do it with sync(). Anyhow I checked the sync implementation and I cant override the sync() method. Thanks anyway. – sudhirk496 Oct 06 '16 at 09:36