用光滑的表达这个查询有更可读或更习惯的方式吗?(Is there a more readable or more idiomatic way of expressing this query with slick?)

我试图使用slick 3.1.1来执行下面的SQL查询的等价物:

SELECT r.* FROM Resource r INNER JOIN User u ON u.id = r.owner_id INNER JOIN UserCredentials uc ON uc.user_id = u.id WHERE r.id = <resource id>

我已经表达了这样的查询:

(for ( ((resource,_),_) <- resources join users on (_.userId === _.id) join userCredentials on (_._2.id === _.userId)) yield resource).filter(_.id === resourceId).result.headOption

它感觉难以阅读和难以阅读。 有没有更清晰的方式来写这个查询与光滑?

I'm trying to use slick 3.1.1 to execute the equivalent of the following SQL query:

SELECT r.* FROM Resource r INNER JOIN User u ON u.id = r.owner_id INNER JOIN UserCredentials uc ON uc.user_id = u.id WHERE r.id = <resource id>

I've expressed the query like this:

(for ( ((resource,_),_) <- resources join users on (_.userId === _.id) join userCredentials on (_._2.id === _.userId)) yield resource).filter(_.id === resourceId).result.headOption

It feels unwieldly and hard to read. Is there a cleaner way of writing this query with slick?

最满意答案

为了理解救援。 内部和交叉连接可以表示为“单点连接”。 以下是使用内部联接:

val query = for { r <- resources if r.id === resourceId u <- users if u.id === r.ownerId uc <- userCredentials if uc.userId === u.id } yield r

查看光滑的文档以获取更多示例。

For comprehension to the rescue. Inner and cross joins can be expressed as "monadic joins". The following is using inner joins:

val query = for { r <- resources if r.id === resourceId u <- users if u.id === r.ownerId uc <- userCredentials if uc.userId === u.id } yield r

Check out slick docs for more examples.

更多推荐