1

我有 3 个模型

Address json
    number Text
    street Text
    pincode Text
    deriving Show
Person json
    email Text
    name Text
    telephone Text
    deriving Show
House json
    rent Int
    ownerId PersonId
    addressId AddressId
    deriving Show

我想访问所有的房子。我可以通过这样做

getHouseR :: Handler Value
getHouseR = do
 houses <- runDB $ selectList [] [Asc HouseRent]
 return $ toJSON houses

但我只参考其他实体,如person & address.

[{"rent":8000,"addressId":4,"ownerId":1,"id":3},{"rent":10000,"addressId":2,"ownerId":1,"id":1}]

我想获得房屋的完整信息,这意味着,解决这个问题ownerId & addressId并发送可能看起来像的数据,

[{"rent":8000,"address":{"number": "23", "street": "12/B", "pincode": "111111"},"owner":{"email": "hey@email.com", "name": "Moto", "telephone": "xxxxxxxxxx"},"id":3}]

有什么方法可以getForiegnData向查询中添加信息,并且可以获取所有这些信息吗?或任何其他解决方案?

4

1 回答 1

0

我找不到任何直接的方法(类似于注释)来获取引用的模型信息。但是有两种方法可以完成这项工作。

  1. 万一,如果您的数据库是 SQL。您可以使用 esqueleto https://github.com/bitemyapp/esqueleto/blob/master/README.md
  2. 编写一些样板代码并获取信息。

创建HouseResp类型,它将代表您的响应正文,包括人员和地址信息。

data HouseResp = HouseResp
  { rent :: Int
  , owner :: Person
  , address :: Address
  }

然后,getHouseR使用可用的参考 ID 进行修改以获取每个房屋的完整信息。

getHouseR :: Handler Value
getHouseR = do
  housesWithReference <- runDB $ selectList [] [Asc HouseRent]
  houses <- sequence (Import.map getCompleteHouse housesWithReference)
  return $ toJSON houses


getCompleteHouse :: Entity House -> Handler HouseResp
getCompleteHouse house = runDB $ do
  let rent' = houseRent (entityVal house)
  person <- getJust (houseOwnerId (entityVal house))
  address' <- getJust (houseAddressId (entityVal house))
  return (HouseResp rent' person address')
于 2019-02-22T14:49:42.263 回答