Ecto:子查询并存在

Ecto: subquery & exists

当 table 中存在关联时,我想向我的模型添加一个标志。在我的用户模型中,我有以下字段:field :is_employed, :boolean, virtual: true, default: false

我可以结合使用 select_mergeexists 吗?

User
|> ...
|> select_merge([u], %{is_employed: Repo.exists(from t in Task, where: u.id == t.user_id and t.status == "in_progress")})
|> Repo.all()
User
|> join(:left, [u], t in Task, on: u.id == t.user_id and t.status == "in_progress")
|> select_merge([u, t], %{is_employed: not is_nil(t) })
|> Repo.all()

解决此问题的一种方法是加入数据,您可以直接使用这些数据来进一步查询适当的数据。