【问题标题】:How to set relation for inner array object in Loopback?如何在 Loopback 中设置内部数组对象的关系?
【发布时间】:2018-03-12 19:27:27
【问题描述】:

我在下面的表格中有数据

{
    "_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" : ""
}

我在这里卡住了。请分享一些解决方案

【问题讨论】:

    标签: loopbackjs strongloop


    【解决方案1】:

    执行以下操作

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

    yourModel embedsMany 回复,回复 belongsTo 用户,用户 有很多回复

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

    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}}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-25
      相关资源
      最近更新 更多