Elixir 外键数组(凤凰城)
我是网络开发的初学者,请原谅我知识的缺乏 我有一个Elixir 外键数组(凤凰城),elixir,phoenix-framework,ecto,Elixir,Phoenix Framework,Ecto,我是网络开发的初学者,请原谅我知识的缺乏 我有一个老师和一个学生外部模式。它们应该通过另一个名为Class的模式通过以下规则链接: 每个班级只有一名教师,并且有一组学生 每个老师都可以参加许多课程 每个学生都可以参加许多课程 以下是我迄今为止构建的模式: # Part of student.ex schema "students" do field :active, :boolean, default: false field :birthday, :date field
老师
和一个学生
外部模式。它们应该通过另一个名为Class
的模式通过以下规则链接:
# Part of student.ex
schema "students" do
field :active, :boolean, default: false
field :birthday, :date
field :email, :string, unique: true
field :firstname, :string
field :lastname, :string
field :phone, :string, unique: true
belongs_to :classes, Class, foreign_key: :class_id
many_to_many :teachers, Users.Teacher, join_through: "classes"
timestamps()
end
这里的情况看起来不错。但问题是,如何在迁移文件中指定“学生ID数组”?以下是迁移功能:
# Part of students migration file. It's the same for teachers.
def change do
create table(:students) do
add :firstname, :string, null: false, size: 32
add :lastname, :string, null: false, size: 32
add :phone, :string, null: false, size: 16
add :email, :string, size: 32
add :birthday, :date
add :active, :boolean, default: false, null: false
timestamps()
end
create(unique_index(:students, [:phone]))
end
这就是我现在真正陷入困境的地方:
def change do
create table(:classes) do
add :title, :string, null: false
add :level, :string
add :hours, :string, null: false
add :start_date, :date
add :end_date, :date
add :teacher_id, references(:teachers), primary_key: true
# HERE! How do I create a column for an array of student_id foreign keys?
timestamps()
end
create(index(:classes, [:teacher_id]))
end
提前感谢。正如我们的文档中所述 您应该在包含外键的表中使用
属于\u to
。想象一个公司员工关系。如果employee
在底层数据库表中包含公司id
,我们说员工
属于公司
。
事实上,当您调用此宏时,将在模式中为您自动定义一个名为外键的字段
相反,既不表示也不表示相应字段的存在。所有的事情都在这个链接的另一端完成
也就是说
学生
模式应具有班级id
字段(已存在)
类
可能应该有教师id
(假设一名教师可能有几节课)。要做到这一点,将教师
改为有很多:类
而不是属于:类
并将类
改为属于:教师
而不是有一个:教师
无论您是否希望学生属于多个班级,模式都不正确。class\u id
外键存在于students
的每个记录中,意味着每个学生都有这个特定的类关联。你应该删除
belongs_to :classes, Class, foreign_key: :class_id
来自学生
,因为它首先将一个学生粘在一个班级里。然后你必须向学生介绍类_
加入模式,如下所述。通过在模式中有很多:学生、用户。学生
。每个学生都有班级id
,就是这样。对不起,我弄错了,所以我删除了评论。我的意思是,这个问题如何解决“每个学生都可以成为多个班级的一部分?”我不希望每个学生只成为一个班级的一部分。我已经更新了答案。我相信,仍然需要在交换类
和教师
以定义谁持有参考键方面进行更改。太棒了!你能补充一下我应该如何在迁移中反映这些变化吗?如何指定多对多关系?我是否需要为多对多
使用references()
,还是只为所属
?
def change do
create table(:classes) do
add :title, :string, null: false
add :level, :string
add :hours, :string, null: false
add :start_date, :date
add :end_date, :date
add :teacher_id, references(:teachers), primary_key: true
# HERE! How do I create a column for an array of student_id foreign keys?
timestamps()
end
create(index(:classes, [:teacher_id]))
end
belongs_to :classes, Class, foreign_key: :class_id