3

我们如何通过查询获得用户对话。理想的做法是查询用户表并加载所有用户对话。例子:

final user = await Amplify.DataStore.query(User.classType, where: User.ID.eq(id))

user.conversations 加载对话列表。

如果无法做到这一点,接下来将是获取具有特定用户的所有对话。示例不工作:

await Amplify.DataStore.query(UserConversation.classType
          where: UserConversation.USER.eq(user.id)
         )

type Message @model @auth(rules: [{allow: public}]) {
  id: ID!
  ConversationId: Conversation @connection
  UserId: User @connection
  body: String
  createdDate: AWSDateTime!
}

type Conversation @model @auth(rules: [{allow: public}]) {
  id: ID!
  date: AWSDateTime
  readBy: [ReadBy] @connection(keyName: "byConversation", fields: ["id"])
  users: [UserConversation] @connection(keyName: "byConversation", fields: ["id"])
  name: String
  image: String
}

type ReadBy @model @auth(rules: [{allow: public}]) @key(name: "byConversation", fields: ["conversationID"]) {
  id: ID!
  date: AWSDateTime
  RedByUsers: User @connection
  conversationID: ID
}

type User @model @auth(rules: [{allow: public}]) {
  id: ID!
  firstName: String
  lastName: String
  userImg: String
  createdDate: AWSDateTime
  updatedDate: AWSDateTime
  email: AWSEmail
  conversations: [UserConversation] @connection(keyName: "byUser", fields: ["id"])
}

type UserConversation @model(queries: null) @key(name: "byUser", fields: ["userID", "conversationID"]) @key(name: "byConversation", fields: ["conversationID", "userID"]) @auth(rules: [{allow: public}, {allow: public}]) {
  id: ID!
  userID: ID!
  conversationID: ID!
  user: User! @connection(fields: ["userID"])
  conversation: Conversation! @connection(fields: ["conversationID"])
}
4

1 回答 1

1

通过执行以下操作,我能够获得第二个版本:

await Amplify.DataStore.query(UserConversation.classType
      where: User.ID.eq(user.id)
     );

上面将执行选择所有用户会话的用户 id 等于user变量 id 的任何内容。起初,您为什么需要为查询传递 User.ID 有点令人困惑,但据我了解,这是由于 AWS DataStore 如何创建 SQL 查询,它在幕后进行连接,并且因此将使用第二个表的列(在本例中为 User 表)来执行连接。我希望我能指出一些关于此的文档,但我找不到任何文档。我只是幸运地尝试了一堆东西,并在错误消息中注意到 SQL 查询是如何生成的。

于 2021-05-15T01:57:05.323 回答