【问题标题】:Can't write double left join using Esqueleto无法使用 Esqueleto 编写双左连接
【发布时间】:2015-01-24 01:10:12
【问题描述】:

我有一个包含教师、学校和学区的数据库架构。 TEACHERS 表有一个可以为空的SCHOOL_ID 列(老师可能属于也可能不属于学校),SCHOOLS 表有一个可以为空的DISTRICT_ID 列(学校可能属于也可能不属于学区)。

使用 Esqueleto,我想要一个教师列表,每个教师都有一个学校(如果他们属于一个学校)和一个学区(如果他们属于一个属于某个学区的学校)。花了一点时间才弄清楚老师的正确表达方式->学校左连接,但我最终还是正确的:

select $
from $ \(teacher `LeftOuterJoin` school) -> do
  on (teacher ^. TeacherSchoolId  ==. school ?. SchoolId)
  return (teacher, school)

我尝试使用类似的表达式在 DISTRICTS 添加另一个左连接:

select $
from $ \(teacher `LeftOuterJoin` school `LeftOuterJoin` district) -> do
  on (school  ^. SchoolDistrictId ==. district ?. DistrictId)
  on (teacher ^. TeacherSchoolId  ==. school   ?. SchoolId)
  return (teacher, school, district)

但我得到一个错误:

Couldn't match type ‘Entity School’ with ‘Maybe (Entity School)’
Expected type: SqlExpr (Maybe (Entity School))
  Actual type: SqlExpr (Entity School)
In the first argument of ‘(?.)’, namely ‘school’
In the second argument of ‘(==.)’, namely ‘school ?. SchoolId’

这个双重连接可以用 Esqueleto 来表达吗?如果有,怎么做?

【问题讨论】:

  • 我不知道这个库,它看起来很复杂,但看起来你需要提升一些 Maybe 的东西才能与 SQL 的东西同步。或者反过来。我不知道。

标签: haskell esqueleto


【解决方案1】:

尝试改变

 on (teacher ^. TeacherSchoolId  ==. school   ?. SchoolId)

 on (teacher ^. TeacherSchoolId  ==. just (school   ?. SchoolId))

如果这不起作用,请在查询表达式的其他组件上“只”处理,直到它起作用为止。

参考:最近在一个商业项目中使用过 Esqueleto

2016 年 10 月 26 日更新:

我最近遇到了这个问题。我认为这是一个持久的序列化问题,与 Esqueleto 愿意假装连接不会产生可为空的结果交互。

我最近更改了一个查询的片段:

  person  `LeftOuterJoin`
  personExtra
 ) -> do
  on ((personExtra ^. PersonExtraPerson) ==. (person ^. PersonId))

到:

  person  `LeftOuterJoin`
  personExtra
 ) -> do
  on ((personExtra ?. PersonExtraPerson) ==. just (person ^. PersonId))

我还将查询的返回类型从Entity PersonExtra 更改为Maybe (Entity PersonExtra)

现在 Persistent 预计 PersistNull 的可能性,并且查询对我来说很好。

【讨论】:

  • 我已经尝试了在两个 ==. 运算符的四个参数中的每一个周围有和没有 just 的所有十六种组合。它们都不会产生可编译的代码。
  • @Sean ?. 是怎么回事?
  • 根据 Esqueleto 文档,它是“从可能(实体 a)投影一个字段”。
  • @Sean 尝试使用上述just 的组合将它们翻转到^.。我知道组合学/情况很荒谬,但 Esqueleto 中基于类型的推理非常困难。有相当多的任意行为。
  • 是否有一个更健全的软件包,每个人都应该改用?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-29
  • 2019-06-17
  • 2014-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多