Yesod / Persistent一对一查询(Yesod/Persistent one-to-one query)

说,在Yesod / Persistent中,我有模型设置如下:

User ident Text password Text Maybe UniqueUser ident Question title Text asker UserId Eq

我有一个Question列表,并希望检索User的相应列表。 我会如何去做这件事?

我曾考虑过连接,但这些是一对多的,而不是一对一的(我想这并不重要,但我想要一个更简单的解决方案)。 手动进行连接也是一种选择,但我担心性能 - 我有

questions <- runDB $ selectList [QuestionTitle !=. ""] [LimitTo 10] let askerIds = map (\(Entity _ q) -> questionAsker q) questions askers <- sequence $ map (runDB . get) askerIds let questionsAndAskers = zip questions askers

但我担心在map使用runDB (它不会为每个用户向数据库提出单独的请求吗?)

有没有更好的/更习惯的方式来实现这一目标?

Say, in Yesod/Persistent, I have models setup like so:

User ident Text password Text Maybe UniqueUser ident Question title Text asker UserId Eq

And I have a list of Questions, and would like to retrieve the corresponding list of Users. How would I go about doing this?

I've thought about joins, but those are one-to-many, not one-to-one (I suppose it doesn't matter, but I'd like a simpler solution). Manually doing the join is also an option, but I'm worried about performance - I have

questions <- runDB $ selectList [QuestionTitle !=. ""] [LimitTo 10] let askerIds = map (\(Entity _ q) -> questionAsker q) questions askers <- sequence $ map (runDB . get) askerIds let questionsAndAskers = zip questions askers

but I'm worried about using runDB in the map (wouldn't it make a separate request to the database for each user?)

Is there a better/more idiomatic way to achieve this?

最满意答案

我还没有对此进行类型检查,但是我会将整个事件粘贴到runDB :

runDB $ selectList [QuestionTitle !=. ""] [LimitTo 10] >>= mapM (\qe@(Entity _ q) -> do asker <- get $ questionAsker q return (qe, asker))

I haven't type-checked this yet, but I would stick the whole thing inside of runDB:

runDB $ selectList [QuestionTitle !=. ""] [LimitTo 10] >>= mapM (\qe@(Entity _ q) -> do asker <- get $ questionAsker q return (qe, asker))

更多推荐