环回中的多个包含模型

时间:2018-01-28 07:28:25

标签: node.js filter include models loopbackjs

嗨,我正在使用loopback 3,我需要执行此查询:

select nbd.Comment.id as commentId, 
       nbd.Comment.content as commentConted, 
       commentCreator.id as userCommentId,
       commentCreator.username userComment,
       reply.id as replyId,
       reply.content as replyContent,
       replyCreator.id as replyUserId,
       replyCreator.username as replyUser 
from nbd.Comment 
inner join nbd.User commentCreator on (nbd.Comment.userId = 
commentCreator.id)
left join nbd.Comment reply on (nbd.Comment.commentParentId = 
reply.commentParentId)
left join nbd.User replyCreator on (reply.userId = replyCreator.id)

所以,为此,我使用了这个包含过滤器:

{
"include": {
    "relation": "user",
    "scope": {
      "fields": [
        "id",
        "username"
      ]
    },
    "relation1": "comments",
    "scope1": {
      "include": [
        "user"
      ]
    }
  }
}

但是,它不起作用......

以下是上下文,评论由用户创建,评论也可以有一个也由用户创建的回复。

这是comment模型关系:

"relations": {
    "user": {
      "type": "belongsTo",
      "model": "MyUser",
      "foreignKey": "userId"
    },
    "comment": {
      "type": "belongsTo",
      "model": "Comment",
      "foreignKey": "commentParentId"
    },
    "comments": {
      "type": "hasMany",
      "model": "Comment",
      "foreignKey": "commentParentId"
    }

这是与my-user的{​​{1}}模型关系:

comments

1 个答案:

答案 0 :(得分:0)

解决方案很简单,如果有人想对一个类似的查询或多个包含在同一级别的环回中,请参见以下示例:

{
  "where": {
    "field": 1
  },
  "order": "field DESC",
  "include": [
    {
      "relation": "relation1",
      "scope": {
        "fields": [
          "field1",
          "field2",
          "field3"
        ],
        "where": {
          "field2": {
            "gt": 2
          }
        }
      }
    },
    {
      "relation": "relation2",
      "scope": {
        "fields": [
          "field1",
          "field2",
          "field3",
          "field4"
        ]
      }
    }
  ]
}

有了这些结构,就可以生成包含的倍数,带有include的查询最重要的方面是关系,必须明确定义这些关系。