Postgresql 是否有可能在EXTO的多个关联中添加额外的字段?
我是外星人的新手。我在Ecto模式中定义了三个表,分别是User、Role和UserRole。在UserRole中,我需要更新与用户和角色表关联的附加字段(如“状态”),这将在UserRole表中创建一个条目Postgresql 是否有可能在EXTO的多个关联中添加额外的字段?,postgresql,phoenix-framework,ecto,Postgresql,Phoenix Framework,Ecto,我是外星人的新手。我在Ecto模式中定义了三个表,分别是User、Role和UserRole。在UserRole中,我需要更新与用户和角色表关联的附加字段(如“状态”),这将在UserRole表中创建一个条目 // User Schema schema "users" do field :first_name, :string field :last_name, :string field :email, :string many_to_many :roles,
// User Schema
schema "users" do
field :first_name, :string
field :last_name, :string
field :email, :string
many_to_many :roles, Role, join_through: "userroles"
end
// Role Schema
schema "roles" do
field :code, :string
field :description, :string
many_to_many :users, User, join_through: "userroles"
end
// UserRole Schema
schema "userroles" do
field :is_default, :boolean, default: false
field :status, :string
field :user_id, :id
field :role_id, :id
belongs_to :users, User, define_field: false
belongs_to :roles, Role, define_field: false
end
//以下是我所做的步骤
// User Schema
schema "users" do
field :first_name, :string
field :last_name, :string
field :email, :string
many_to_many :roles, Role, join_through: "userroles"
end
// Role Schema
schema "roles" do
field :code, :string
field :description, :string
many_to_many :users, User, join_through: "userroles"
end
// UserRole Schema
schema "userroles" do
field :is_default, :boolean, default: false
field :status, :string
field :user_id, :id
field :role_id, :id
belongs_to :users, User, define_field: false
belongs_to :roles, Role, define_field: false
end
aroleChangeset=Role.changeset(%Role{},%%代码:“CON”,说明:“消费者”})
brole1=Repo.insert!(roleChangeset)defmodule YourApp.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
...
has_many :user_roles, YourApp.UserRole
end
def changeset(user, params) do
user
|> cast_things...
|> cast_assoc(:user_roles)
end
end
…因为您的用户从不更改可用的角色。只是用户角色。这会让你做一些像
user=YourApp.Repo.get(YourApp.user,1)
这是可能的。然而,我个人发现使用
cast_assoc
有时很难理解,尤其是在给定的情况下,因此我倾向于直接处理连接表。这就是为什么我在上面的评论中提到,我对上面的第9步和第10步不起作用感到困惑。我对上面的第9步和第10步感到困惑。看起来你在#9中没有做任何改变?您是如何在#10中获得状态:“活动的”
?如果你在#10中得到了一些东西,它应该反映在数据库中Repo.get_by
应将相同的值返回到先前的Repo.update
。不知道如何帮助…@Lanny Bose,我错过了在上午9点之间发布步骤。和#9 b。首先很抱歉。我会更新我的问题我已经更新了我的问题。我不知道为什么在执行了#9a、#9b和#9c中的步骤后,它没有反映在db中。我做错什么了吗。如果我错了,请纠正我。啊。。。问题是,你误用了上面的change/2
:看看上面文档中的例子。上面的B行不会产生任何更改。相反,对于#11,您需要exto.Changeset.change(fetchUserRole,%{status:“Active”})
。是的,他们打算为9和10使用预定义的角色,我试着像我提到的那样,但它在iex中显示了结果,但在db中没有反映出来。现在我为用户和角色表使用了has_many:user_roles,YourApp.UserRole。我可以通过执行以下操作来更新它。A.user_role=Repo.get_by(UserRole,id:1),b。用户|角色|>UserRole.changeset(%%{status:“Active”})|>Repo.update()