Select 用户提交了考勤卡

Select users where timecard submitted

假设我有一些用户:

| id | name  |
|----|-------|
| 1  | bob   |
| 2  | bill  |
| 3  | barry |

这些用户每周提交考勤卡:

| id | date         | user_id | week |
|----|--------------|---------|------|
| 1  | '2018-01-01' | 1       | 1    |
| 2  | '2018-01-02' | 1       | 1    |
| 3  | '2018-01-01' | 2       | 1    |

我现在想编写一个 ecto 查询,其中 return 是已提交给定周时间卡的用户列表。

我尝试了以下方法:

def get_users_with_timecards(week) do
  import Ecto.Query, only: [from: 2]

  from(u in User,
    join: tc in Timecard,
    where: tc.week== ^week,
    distinct: u.id
  )
  |> Repo.all()
end

运行以下,我得到:

iex>get_users_with_timecards(1) |> length
3

我只想 return 前 2 位用户 - 已提交考勤卡的用户。

我错过了 from/2 中的 on: 部分。以下对我有用:

def get_users_with_timecards(week) do
  import Ecto.Query, only: [from: 2]

  from(u in User,
    join: tc in Timecard,
    on: u.id == tc.user_id,
    where: tc.week== ^week,
    distinct: u.id
  )
  |> Repo.all()
end

如果您的架构设置了 belongs_tohas_many 关系,您也可以这样做..

from(u in User,
join: tc in assoc(u, :timecards),
where: tc.week== ^week,
    distinct: u.id
  )
  |> Repo.all()