php – Laravel在Eloquent mutators中保存了多对多的关系
发布时间:2020-12-14 19:49:30 所属栏目:大数据 来源:网络整理
导读:我有两个具有多对多关系的模型.我希望能够使用一组id设置一个特定的属性,并在mutator中建立这样的关系: ?phpclass Profile extends Eloquent { protected $fillable = [ 'name','photo','tags' ]; protected $appends = [ 'tags' ]; public function getTag
我有两个具有多对多关系的模型.我希望能够使用一组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,))
在保存模型之前,不能附加多对多关系.在设置$model->标签之前在模型上调用save(),你应该没问题.原因是模型需要具有Laravel可以放入数据透视表的ID,这需要两个模型的ID.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |