【问题标题】:Update to-many association更新对多关联
【发布时间】:2015-01-06 06:49:38
【问题描述】:

在用户和组之间具有多对多的关系。我想知道如何更新与 SDR 的这种关系。这是我在阅读docs 后到目前为止所尝试的。

curl -X POST -H 'Content-Type: text/uri-list' -d 'http://localhost:8080/rest/users/5' http://localhost:8080/rest/groups/1/users

预期结果:将用户 5 添加到组 1。

实际结果:405 Method Not Allowed。

curl -X PUT -H 'Content-Type: text/uri-list' -d 'http://localhost:8080/rest/users/5' http://localhost:8080/rest/groups/1/users

预期结果:将组 1 的所有成员替换为用户 5。

实际结果:按预期工作。

curl -X PUT -H 'Content-Type: text/uri-list' -d @members.txt http://localhost:8080/rest/groups/1/users

members.txt 文件所在的位置:

http://localhost:8080/rest/users/5
http://localhost:8080/rest/users/6
http://localhost:8080/rest/users/7

预期结果:将组 1 的所有成员替换为用户 5、6 和 7。

实际结果:仅添加最后一个用户(在本例中为 7)。

有人可以提供一个关于如何将单个 URI 添加到关联的示例吗?另外,如果可能的话,如何添加或替换具有多个 URI 的关联?

【问题讨论】:

    标签: spring spring-boot spring-data-rest


    【解决方案1】:

    重新阅读文档后,确实说 POST 应该添加到集合中。

    我的经验是使用 PATCH 添加到集合中。

    进一步回答:您应该能够将 PUT CONTENT-TYPE: text/uri-list 与具有多个 URI 的内容主体一起使用。每个 URI 由换行符“\n”分隔

    【讨论】:

    • 嗨@Brandon。感谢您的回复,我会尝试使用 PATCH 看看效果如何。至于将 PUT 与多个 URI 一起使用,这正是我在上面最后一次测试中所做的。结果是只有最后一个 URI 被添加到集合中。
    • 上次测试是使用文件上传。我相信 curl 在使用文件时会去掉换行符。尝试使用curl -X PUT -H 'Content-Type: text/uri-list' -d "http://localhost:8080/rest/users/5 \n http://localhost:8080/rest/users/6 \n http://localhost:8080/rest/users/7" http://localhost:8080/rest/groups/1/users
    • 如果你想从收藏中删除项目怎么办?
    • @BrandonBrooks 只缺少一件事。我还必须执行以下操作:curl -X PUT -H 'Content-Type: text/uri-list' -d $'http://localhost:8080/rest/users/6\r\nhttp://localhost:8080/rest/users/7' http://localhost:8080/rest/groups/1/users(空行)关键是添加$' 来开始数据和' 来结束数据块,以及在中间使用\r\n 并且没有空格。
    • @Piotr curl -X DELETE http://localhost:8080/rest/groups/1/users/5 。相关阅读:stackoverflow.com/questions/28679934/…
    【解决方案2】:

    试试这个:

    curl -v -X POST -H "Content-Type: text/uri-list" -d "http://localhost:8080/rest/users/5" http://localhost:8080/rest/groups/1/users
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      相关资源
      最近更新 更多