假设我有一些用户:
| 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 查询,它返回在给定一周内提交考勤卡的用户列表。
我尝试了以下方法:
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
我只想返回前 2 个用户 - 那些已提交考勤卡的用户。
如果您的架构设置了belongs_to
和has_many
关系,您也可以这样做。
from(u in User,
join: tc in assoc(u, :timecards),
where: tc.week== ^week,
distinct: u.id
)
|> Repo.all()
我错过了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