Elixir-Exto:如何存储关于多对多关系的元信息
假设我有Elixir-Exto:如何存储关于多对多关系的元信息,elixir,ecto,Elixir,Ecto,假设我有用户和组织模型,以及两者之间的多对多关系。我现在想补充关于两者之间关系的信息。例如时间戳和位置。我该怎么做?我该如何查询这些信息 我认为正确的方向是使用连接模式。以下是类似于以下内容的EXTO文档: defmodule UserOrganization do use Ecto.Schema @primary_key false schema "users_organizations" do field :position, :string # adding info
用户
和组织
模型,以及两者之间的多对多关系。我现在想补充关于两者之间关系的信息。例如时间戳
和位置
。我该怎么做?我该如何查询这些信息
我认为正确的方向是使用连接模式。以下是类似于以下内容的EXTO文档:
defmodule UserOrganization do
use Ecto.Schema
@primary_key false
schema "users_organizations" do
field :position, :string # adding information on the position of the user within the organization
belongs_to :user, User
belongs_to :organization, Organization
timestamps # Added bonus, a join schema will also allow you to set timestamps
end
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:user_id, :organization_id])
|> Ecto.Changeset.validate_required([:user_id, :organization_id])
# Maybe do some counter caching here!
end
end
defmodule User do
use Ecto.Schema
schema "users" do
many_to_many :organizations, Organization, join_through: UserOrganization
end
end
defmodule Organization do
use Ecto.Schema
schema "organizations" do
many_to_many :users, User, join_through: UserOrganization
end
end
# Then to create the association, pass in the ID's of an existing
# User and Organization to UserOrganization.changeset
changeset = UserOrganization.changeset(%UserOrganization{}, %{user_id: id, organization_id: id})
case Repo.insert(changeset) do
{:ok, assoc} -> # Assoc was created!
{:error, changeset} -> # Handle the error
end
现在,在创建记录时,如何设置
位置
,如何查询时间戳
和位置
?如果要检索复合模式的时间戳
和位置
,您可以添加在用户
和组织
,像这样
defmodule Organization do
use Ecto.Schema
schema "organizations" do
many_to_many :users, User, join_through: UserOrganization
has_many :user_organizations, UserOrganization
end
end
然后,当您检索Organization
时,您可以Repo.preload
关系user\u Organization
,并且UserOrganization
的所有属性都将对您可用
关于如何设置位置
,您只需将其添加到变更集中,并确保允许用户组织
架构上的参数
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.cast(params, [:user_id, :organization_id, :position])
|> Ecto.Changeset.validate_required([:user_id, :organization_id])
# Maybe do some counter caching here!
end
changeset = UserOrganization.changeset(%UserOrganization{}, %{user_id: id, organization_id: id, position: position})
这对你来说应该很好