【问题标题】:How to fill the related model on a many 2 many association?如何在多 2 多关联上填充相关模型?
【发布时间】:2023-03-29 03:32:01
【问题描述】:

使用 ember-data,我有这两个模型:

App.Post = DS.Model.extend
  title: DS.attr "string"
  body: DS.attr "string"
  categories: DS.hasMany "App.Category"

App.Category = DS.Model.extend
  name: DS.attr "string"
  posts: DS.hasMany 'App.Post'

还有这个序列化:

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, :body

  has_many :categories
  embed :ids, include: true
end

class CategorySerializer < ActiveModel::Serializer
  attributes :id, :name
end

当我请求帖子时,我得到了预期的 JSON,并且我可以毫无问题地访问帖子的类别,但是如果我请求类别(我认为它们被缓存),我得到的类别与帖子没有任何关系。它甚至不会尝试发出 get 请求(这也不起作用)。

那么,类别的帖子关系不应该被填满吗?

不确定我是否错过了 ember 或 AMS 中的某些内容(我认为类别序列化程序应该知道有很多帖子)

【问题讨论】:

标签: ember.js many-to-many ember-data active-model-serializers


【解决方案1】:

好吧,在与 IRC 的一些人苦苦挣扎后,我最终得出了这个解决方案,我希望它对其他人有所帮助,并且可能会有所改进。

问题是类别没有任何帖子参考,所以如果你要求帖子,你会得到带有类别的帖子,但类别本身对帖子一无所知。

如果我尝试做类似的事情:

class CategorySerializer < ActiveModel::Serializer
  attributes :id, :name

  has_many :posts
  embed :ids, include: true
end

它会爆炸,因为它们相互引用,你会得到“太深层次”或类似的东西。

你可以这样做:

class CategorySerializer < ActiveModel::Serializer
  attributes :id, :name

  has_many :posts, embed: :objects
end

它会起作用,但结果 JSON 将是巨大的,因为当您请求帖子时,您会得到每条帖子 + 每条评论,并且在其中,每条帖子都具有该类别......不爱

那么这个想法是什么?有类似的东西:

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, :body

  has_many :categories
  embed :ids, include: true
end

class CategorySerializer < ActiveModel::Serializer
  attributes :id, :name

  has_many :posts, embed: :ids
end

对于每个帖子,您都会获得 categories_ids,对于您引用的每个类别,您只能获得其属性和属于该类别的帖子的 ID(而不是整个对象)。

但是当您转到“/#/categories”并且您还没有加载帖子时会发生什么?好吧,由于您的 CategorySerializer 不会序列化任何帖子,因此您将一无所获。

因此,由于您不能在序列化程序之间进行交叉引用,因此我以 4 个序列化程序结束。 2 用于帖子及其类别,2 用于类别及其帖子(因此,无论您先加载帖子还是类别都无关紧要):

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, :body

  has_many :categories, serializer: CategoriesForPostSerializer
  embed :ids, include: true
end

class CategoriesForPostSerializer < ActiveModel::Serializer
  attributes :id, :name

  has_many :posts, embed: :ids
end

class CategorySerializer < ActiveModel::Serializer
  attributes :id, :name

  has_many :posts, serializer: PostsForCategorySerializer
  embed :ids, include: true
end

class PostsForCategorySerializer < ActiveModel::Serializer
  attributes :id, :title, :body

  has_many :categories, embed: :ids
end

这可以解决问题。但由于我是 Ember 的新手,而且我不是 JSON 设计的专家。如果有人知道一种简单的方法或者可能做了一些嵌入(总是或加载到适配器中,我还不明白),请评论:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2014-12-14
    • 2012-12-24
    • 1970-01-01
    相关资源
    最近更新 更多