如果条件失败,Elixir / Phoenix查询将返回空

时间:2017-02-03 14:07:16

标签: elixir phoenix-framework ecto

我试图通过在查询中加入另一个表来返回该值,但是如果从辅助表中找到非值,是否仍然可以在最终结果中包含该元素?

这是我的问题:

 Repo.all(from p in Subjectclass, where: p.user_id == ^user.id,
                                          join: f in Subject,
                                          on: p.subject_id == f.id,
                                          join: z in Schedule,
                                          on: f.id == z.subject_id,
                                          where: z.weekday == 1,
                                          join: t in User,
                                          on: f.user_id == t.id,
                                          join: h in Homework,
                                          on: f.id == h.subject_id,
                                          where: h.deadline == ^this_monday,
                                          group_by: f.title,
                                          group_by: t.surname,
                                          group_by: z.timeslot_id,
                                          group_by: h.body,
                                          order_by: z.timeslot_id,
                                          select: %{title: f.title, teacher: t.surname, homework: h.body})

where: h.deadline == ^this_monday,会检查主题当天是否有任何家庭作业。但如果没有(主题没有作业),它只是从最终结果中删除了整个元素。

我的问题:是否有可能仍然包含没有作业的元素(即标题:"数学",老师:" Bob",作业:"&#34 ;)在最终结果(选择:),或以某种方式替代空间?在当前代码中,它只是从最终结果中删除整个元素。

提前谢谢!

架构:

schema "subjectclasses" do
  belongs_to :user, Kz.User
  belongs_to :subject, Kz.Subject
  timestamps()
end

schema "subjects" do
  field :lvl, :integer
  field :title, :string
  field :week, :integer
  belongs_to :user, Kz.User
  has_many :subjectclasses, Kz.Subjectclass
  timestamps()
end

schema "schedules" do
  field :subject_id, :integer
  field :weekday, :integer
  belongs_to :timeslot, Kz.Timeslot  
  timestamps()
end

schema "users" do
  field :firstname, :string
  field :surname, :string
  field :level, :integer
  field :username, :string
  field :encrypted_password, :string
  belongs_to :role, Kz.Role
  has_many :subjects, Kz.Subject
  has_many :subjectclasses, Kz.Subjectclass
  field :password, :string, virtual: true
  timestamps()
end

schema "homeworks" do
  field :body, :string
  field :deadline, Ecto.Date
  belongs_to :subject, Kz.Subject
  timestamps()
end

1 个答案:

答案 0 :(得分:0)

解决它:

left_join: h in Homework,
on: f.id == h.subject_id and h.deadline == ^this_monday,

以便连接位于Homework表中的唯一字段。