【发布时间】:2020-04-22 06:26:02
【问题描述】:
我是网络开发的初学者,所以请原谅我缺乏知识。
我有一个Teacher 和一个Student Ecto 架构。它们应该通过另一个名为 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
# Part of teacher.ex
schema "teachers" 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 :students, Users.Student, join_through: "classes"
timestamps()
end
# Part of class.ex
schema "classes" do
field :end_date, :date
field :time, :time
field :level, :string
field :start_date, :date
field :title, :string
has_many :students, Users.Student
has_one :teacher, Users.Teacher
embeds_many :sessions, Session
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
提前致谢。
【问题讨论】:
标签: elixir phoenix-framework ecto