2

我有三个模型:用户、图片和点赞

在哪里:

class Picture
    include Mongoid::Document
    embeds_many :likes
    belongs_to :user
end
class User
    include Mongoid::Document
    has_many :pictures
    has_many :likes
end
class Like
    include Mongoid::Document
    belongs_to :user
    embedded_in :picture
end

不,我想将喜欢的内容存储到:

  • 查看有多少赞有一张图片( Picture.first.likes.count )
  • 查看用户有多少喜欢( User.first.likes.count )
  • 看看用户点赞了哪些图片?

这个 Schema 是否正确地实现了这三个要求?

4

1 回答 1

2

首先,嵌入模型无法在其他用户中引用,就像您尝试在 User 中引用 Like(已嵌入图片中)一样。

正确的模型结构将是

class Picture
    include Mongoid::Document
    has_and_belongs_to_many :likers, :class_name => "User", :inverse_of => nil
    belongs_to :user
end

class User
    include Mongoid::Document
    has_many :pictures
end

现在回答您的疑问

# See how many likes have a picture
Picture.first.likers.count
# See how many likes a user has
# (assumption - will have only one like from one user for a specific picture)
Picture.where(:liker_ids => User.first).count
# See to what picture the user make a like?
Picture.where(:liker_ids => User.first).all
于 2012-09-07T14:00:09.147 回答