如何在Loopback中设置内部数组对象的关系?

时间:2018-03-06 11:11:09

标签: loopbackjs strongloop

我在下表中有数据

{
    "_id" : ObjectId("5a9d1b70b826170df4365489"),
    "userId" : "5a93e0b76d32cd0e6c1b99aa",
    "mediaId" : "5a99330af218d30c981cda2f",
    "comment" : "Hi this is a video",
    "**replies**" : [ 
        {
            "comment" : "this is a reply 1",
            "**userId**" : "5a93e0b76d32cd0e6c1b99aa"
        }, 
        {
            "comment" : "this is a reply 2",
            "**userId**" : "5a93e0b76d32cd0e6c1b99aa"
        }, 
        {
            "comment" : "this is a reply 3",
            "**userId**" : "5a93e0b76d32cd0e6c1b99aa"
        }
    ],
    "createdAt" : "",
    "updatedAt" : ""
}

我的问题: 如何在环回中的每个回复数组对象中为userId设置关系并包含来自用户表的数据?

我预期的输出:

{
    "_id" : ObjectId("5a9d1b70b826170df4365489"),
    "userId" : "5a93e0b76d32cd0e6c1b99aa",
    "mediaId" : "5a99330af218d30c981cda2f",
    "comment" : "Hi this is a video",
    "**replies**" : [ 
        {
            "comment" : "this is a reply 1",
            "**userId**" : "5a93e0b76d32cd0e6c1b99aa",
            "userDetails":{
               "name":"xxxxxxxxx",
               "address":"xxxxxxxx"
            }

        }, 
        {
            "comment" : "this is a reply 2",
            "**userId**" : "5a93e0b76d32cd0e6c1b99aa",
            "userDetails":{
               "name":"xxxxxxxxx",
               "address":"xxxxxxxx"
            }
        }, 
        {
            "comment" : "this is a reply 3",
            "**userId**" : "5a93e0b76d32cd0e6c1b99aa",
            "userDetails":{
               "name":"xxxxxxxxx",
               "address":"xxxxxxxx"
            }
        }
    ],
    "createdAt" : "",
    "updatedAt" : ""
}

我被困在这里。亲切地分享一些解决方案

1 个答案:

答案 0 :(得分:0)

执行以下操作

  1. 创建3个模型:yourModel,user,reply
  2. relations中设置这些model definition json或使用node api:
  3.   

    yourModel embedsMany 回复,回复 belongsTo 用户,用户    hasMany 回复

    1. 使用字符串化的json作为包含过滤器
    2. 查询数据

      https://loopback.io/doc/en/lb3/Querying-data.html#using-stringified-json-in-rest-queries

        

      {include:{relatedModel1:[{relatedModel2:'relationName'},'relatedModel']}}

      这样的事可能

      /api/your_model/?filter={"include":{"replies":{"userDetails":true}}}