Laravel在Eloquent mutators中保存了多对多的关系

 gxh123 发布于 2023-02-13 12:41

我有两个具有多对多关系的模型.我希望能够使用一组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 intoprofile_tag (profile_id ,tag_id) values (?, ?)) (Bindings: array ( 0 => NULL, 1 => 1, ))

1 个回答
  • 在保存模型之前,不能附加多对多关系.save()在设置之前调用模型$model->tags,你应该没问题.原因是模型需要具有Laravel可以放入数据透视表的ID,这需要两个模型的ID.

    2023-02-13 12:43 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有