我是网络开发人员的初学者,请原谅我缺乏知识。
我有一个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
提前感谢。
如Ecto.Schema.belongs_to/3
的文档中所述,>
您应该在包含外键的表中使用
Ecto.Schema.belongs_to/3
。想象一下belongs_to
关系。如果company <-> employee
包含基础数据库表中的employee
,则说company_id
属于employee
。实际上,当您调用此宏时,将在您的架构中自动定义一个具有外键名称的字段。相反,
company
和Ecto.Schema.has_one/3
均不暗示相应字段的存在。一切都在此链接的另一端完成。
说,
Ecto.Schema.has_one/3
模式应具有Ecto.Schema.has_many/3
字段(已经存在)]Ecto.Schema.has_many/3
可能应该有students
(假设老师可能有几节课。)要做到这一点,请将class_id
改为classes
而不是teacher_id
andteachers
改为[C0 ]代替has_many :classes
。这些更改应该在我正确理解意图后进行。