Reputation: 957
My pivot table has additional field...
id | user_id | language_id | level
---------------------------------------
and my code:
User::find($this->userId)->languages()->attach(['language_id' => $lang_id, 'level' => $level]);
but the result is:
id | user_id | language_id | level
---------------------------------------
1 1 1 null
1 1 2 null
actually, second line's language_id must be first line's level...
how can i do it properly like this?
id | user_id | language_id | level
---------------------------------------
1 1 1 2
Upvotes: 0
Views: 66
Reputation: 153010
attach()
works a bit differently. The first parameter is the id or an instance of the other model and the second parameter are other pivot fields:
User::find($this->userId)->languages()->attach($lang_id, ['level' => $level]);
As @ceejayoz mentioned you also don't have withPivot()
defined in your relationship. That means level
won't be available in the result. Change that by adding withPivot()
to both sides of the relation:
public function languages() {
return $this->belongsToMany('Language')->withPivot('level');
}
Upvotes: 2