我有两个具有多对多关系的模型.我希望能够使用一组id设置一个特定的属性,并在mutator中建立关系,如下所示:
tags()->get([ 'tag_id' ]); foreach ($tags as $tag) { $tag_ids[] = $tag->tag_id; } return $tag_ids; } public function setTagsAttribute($tag_ids) { foreach ($tag_ids as $tag_id) { $this->tags()->attach($tag_id); } } public function tags() { return $this->belongsToMany('Tag'); } } profiles()->get([ 'profile_id' ]); foreach ($profiles as $profile) { $profile_ids[] = $profile->profile_id; } return $profile_ids; } public function profiles() { return $this->belongsToMany('Profile'); } }
但是该setTagsAttribute
功能未按预期工作.我收到以下错误:SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'profile_id' cannot be null (SQL: insert into
profile_tag (
profile_id ,
tag_id) values (?, ?)) (Bindings: array ( 0 => NULL, 1 => 1, ))
在保存模型之前,不能附加多对多关系.save()
在设置之前调用模型$model->tags
,你应该没问题.原因是模型需要具有Laravel可以放入数据透视表的ID,这需要两个模型的ID.