【问题标题】:sails.js one-to-one association created as one-way associationSails.js 一对一关联创建为单向关联
【发布时间】:2015-02-01 18:35:10
【问题描述】:

我注意到我在帖子上得到的响应与在获取时不同。具体来说,关联。

引用“在与另一条新记录关联时创建新记录” https://github.com/balderdashy/sails-docs/blob/master/reference/blueprint-api/Create.md

我使用 sails new testProjsails generate api ponysails generate api pet 从文档中重新创建场景,然后更新模型以具有一对一关联。

小马

module.exports = {
    attributes: {
        pet: {
            model: 'pet'
        }
    }
};

小马

module.exports = {
    attributes: {
        pet: {
            model: 'pet'
        }
    }
};

宠物

module.exports = {
    attributes: {
        pony: {
            model: 'pony'
        }
    }
};

然后,sails lift 离开。

POST /pony

JSON 请求

{
  "name": "Pinkie Pie",
  "hobby": "ice skating",
  "pet": {
    "name": "Gummy",
    "species": "crocodile"
  }
}

JSON 解析

{
  "name": "Pinkie Pie",
  "hobby": "ice skating",
  "pet": 1,
  "createdAt": "2014-11-21T19:18:09.161Z",
  "updatedAt": "2014-11-21T19:18:09.161Z",
  "id": 1
}

如您所见,response 不包含完整的宠物对象,仅包含其 id。在文档中,它显示了返回的完整对象。

条目和关联肯定创建成功,

GET - /pony/1

{
  "pet": {
    "name": "Gummy",
    "species": "crocodile",
    "createdAt": "2014-11-21T19:18:09.157Z",
    "updatedAt": "2014-11-21T19:18:09.157Z",
    "id": 1
  },
  "name": "Pinkie Pie",
  "hobby": "ice skating",
  "createdAt": "2014-11-21T19:18:09.161Z",
  "updatedAt": "2014-11-21T19:18:09.161Z",
  "id": 1
}

这是文档中的错误,还是代码中的错误?无论哪种方式,有没有一种方法可以指定我们希望返回关联?

一对一的关联只是显示为链接的 id,多对多根本不显示。当我看到showJoins 选项时,我正在研究waterlinetoObject() 函数以解决另一个问题;看起来可能与此有关。

此外,这种一对一关联实际上只是作为单向关联创建的。

完成上述相同后:

GET - /pet/1

{
  "name": "Gummy",
  "species": "crocodile",
  "createdAt": "2014-12-03T20:50:31.346Z",
  "updatedAt": "2014-12-03T20:50:31.346Z",
  "id": 1
}

请注意,没有返回任何小马。

只是为了确保...

GET - /pony/1/pet

{
  "name": "Gummy",
  "species": "crocodile",
  "createdAt": "2014-12-03T20:50:31.346Z",
  "updatedAt": "2014-12-03T20:50:31.346Z",
  "id": 1
}

GET - /pet/1/pony

Res

Specified record (1) is missing relation 'pony'

小马有宠物,宠物没有小马。

我做错了什么?

【问题讨论】:

    标签: model associations sails.js waterline


    【解决方案1】:

    您需要在定义双向关系时提供viaattribute,否则它们会被假定为不相关的单向连接。

    小马

    module.exports = {
        attributes: {
            pet: {
                model: 'pet',
                via: 'pony'
            }
        }
    };
    

    宠物

    module.exports = {
        attributes: {
            pony: {
                model: 'pony',
                via: 'pet'
            }
        }
    };
    

    文档中仅在 many-manyone-many 关系中提及,这可能是一个错误。

    【讨论】:

    猜你喜欢
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    相关资源
    最近更新 更多