【问题标题】:Multiple include model in loopback环回中的多个包含模型
【发布时间】:2018-01-28 07:28:25
【问题描述】:

嗨,我使用的是 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-usercomments的模型关系:

"relations": {
    "comments": {
      "type": "hasMany",
      "model": "Comment",
      "foreignKey": "userId"
    }
  }

【问题讨论】:

    标签: node.js filter include models loopbackjs


    【解决方案1】:

    解决方案很简单,如果有人想通过环回将类似的查询或多个包含在同一级别,这里是示例:

    {
      "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"
            ]
          }
        }
      ]
    }
    

    使用这些结构可以生成多个包含,包含查询的最重要方面是关系,必须很好地定义关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      相关资源
      最近更新 更多