同一模式上的多个关联
Multiple associations on same schemas
使用 Ecto v2.2.6,phoenix 1.3
我有一个场景,用户可以创建帖子,然后其他用户可以喜欢帖子。用户通过创建与帖子具有一对多关系,通过链接与喜欢具有多对多关系table。
设置:
mix phx.gen.json Account User users name:string
mix phx.gen.json Content Post posts title:string content:text user_id:references:users
mix phx.gen.json Content Like likes user_id:references:users post_id:references:posts
模式:
schema "users" do
field :name, :string
has_many :posts, SocialNetwork.Content.Post, foreign_key: :users_id
many_to_many :posts, SocialNetwork.Content.Post, join_through: "likes"
timestamps()
end
schema "posts" do
field :content, :string
field :title, :string
belongs_to :user, SocialNetwork.Accounts.User
many_to_many :users, SocialNetwork.Accounts.User, join_through: "likes"
timestamps()
end
schema "likes" do
belongs_to :user, SocialNetwork.Accounts.User
belongs_to :post, SocialNetwork.Content.Post
timestamps()
end
当我 运行 混合 phx.server 时,我得到这个错误:
== Compilation error in file lib/social_network/account/user.ex ==
** (ArgumentError) field/association :posts is already set on schema
有没有一种方法可以通过不同的上下文为同一架构设置多个关联?
Is there a way that I can set up more than one association to the same schema, but through a different context?
可以,但是您必须为这两个协会选择不同的名称,例如:
has_many :posts, SocialNetwork.Content.Post, foreign_key: :users_id
many_to_many :liked_posts, SocialNetwork.Content.Post, join_through: "likes"
您不需要修改 Post
中的任何内容,因为 Post
已经为两个关联使用了不同的名称。
使用 Ecto v2.2.6,phoenix 1.3
我有一个场景,用户可以创建帖子,然后其他用户可以喜欢帖子。用户通过创建与帖子具有一对多关系,通过链接与喜欢具有多对多关系table。
设置:
mix phx.gen.json Account User users name:string
mix phx.gen.json Content Post posts title:string content:text user_id:references:users
mix phx.gen.json Content Like likes user_id:references:users post_id:references:posts
模式:
schema "users" do
field :name, :string
has_many :posts, SocialNetwork.Content.Post, foreign_key: :users_id
many_to_many :posts, SocialNetwork.Content.Post, join_through: "likes"
timestamps()
end
schema "posts" do
field :content, :string
field :title, :string
belongs_to :user, SocialNetwork.Accounts.User
many_to_many :users, SocialNetwork.Accounts.User, join_through: "likes"
timestamps()
end
schema "likes" do
belongs_to :user, SocialNetwork.Accounts.User
belongs_to :post, SocialNetwork.Content.Post
timestamps()
end
当我 运行 混合 phx.server 时,我得到这个错误:
== Compilation error in file lib/social_network/account/user.ex ==
** (ArgumentError) field/association :posts is already set on schema
有没有一种方法可以通过不同的上下文为同一架构设置多个关联?
Is there a way that I can set up more than one association to the same schema, but through a different context?
可以,但是您必须为这两个协会选择不同的名称,例如:
has_many :posts, SocialNetwork.Content.Post, foreign_key: :users_id
many_to_many :liked_posts, SocialNetwork.Content.Post, join_through: "likes"
您不需要修改 Post
中的任何内容,因为 Post
已经为两个关联使用了不同的名称。