我有两个具有多对多关系的模型.我希望能够使用一组id设置一个特定的属性,并在mutator中建立这样的关系:
<?PHP class Profile extends Eloquent { protected $fillable = [ 'name','photo','tags' ]; protected $appends = [ 'tags' ]; public function getTagsAttribute() { $tag_ids = []; $tags = $this->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'); } } <?PHP class Tag extends Eloquent { protected $fillable = [ 'title' ]; protected $appends = [ 'profiles' ]; public function getProfilesAttribute() { $profile_ids = []; $profiles = $this->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]:完整性约束违规:1048列’profile_id’不能为空(sql:insert intoprofile_tag(profile_id,tag_id)值(?,?))(绑定:数组(0 => ; NULL,1 => 1,))