序列化与 Phoenix 的多对一关系
Serializing many to one relation with Phoenix
我正在寻找某种 tutorial/example 将结构序列化为 json 和 Phoenix 应用程序中的 Poison 库。我找到了这样的例子:https://robots.thoughtbot.com/building-a-phoenix-json-api but it's not using Poison and it isn't covering structs with nested map of structs. I've also tried this answer: 但我没能正确地实现它。我想从我的控制器序列化与另一个结构具有 has_many 关系的结构映射。有没有人见过这样的事情或者可以帮助我处理这样的情况?
您可以简单地使用 defimpl
作为 Poison.Encoder 协议并实现自定义 encode
。
您将需要直接在模型文件中执行此操作,这样您就可以添加其他字段或只是确保正确加载关系。
要获取关系项,您只需将私有函数与 assoc/2 一起使用,然后将其用作 encode
中的字段。
我正在寻找某种 tutorial/example 将结构序列化为 json 和 Phoenix 应用程序中的 Poison 库。我找到了这样的例子:https://robots.thoughtbot.com/building-a-phoenix-json-api but it's not using Poison and it isn't covering structs with nested map of structs. I've also tried this answer:
您可以简单地使用 defimpl
作为 Poison.Encoder 协议并实现自定义 encode
。
您将需要直接在模型文件中执行此操作,这样您就可以添加其他字段或只是确保正确加载关系。
要获取关系项,您只需将私有函数与 assoc/2 一起使用,然后将其用作 encode
中的字段。