选择提交时间表的用户

时间:2019-10-22 14:27:45

标签: elixir ecto

说我有一些用户:

.on( 'click' , function (evt){
     evt.stopPropagation();
 })

这些用户每周提交一次时间表:

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

我现在想编写一个ecto查询,该查询返回已提交给定一周的时间卡的用户列表。

我尝试了以下方法:

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

运行以下命令,我得到:

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

我只想返回前2个用户-提交了时间卡的用户。

2 个答案:

答案 0 :(得分:2)

如果您的架构建立了belongs_tohas_many关系,那么您也可以这样做。

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

答案 1 :(得分:1)

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

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