gpt4 book ai didi

javascript - Sails.js:如何使用模型关联填充数组

转载 作者:行者123 更新时间:2023-11-30 17:30:30 25 4
gpt4 key购买 nike

我正在使用“sails”:“~0.10.0-rc5”,“sails-mongo”:“^0.10.0-rc3”。我有 2 个模型:发票、项目。

发票模型

Invoice: {
name: 'sample 1',
items: [1,2] // 1,2 is id of Item model
}

元素模型

Item {
id: 1,
name: "king"
}
Item {
id: 2,
name: 'queen'
}

我希望结果是:

Invoice: {
name: 'sample 1',
items: [{
id: 1,
name: "king"
}, {
id: 2,
name: 'queen'
}]
}

我读了model associations from the sails docs但我不知道如何在我的情况下使用它。

最佳答案

您的 item 模型将如下所示:

attributes: {
name: "STRING"
// You don't need the ID field as this is automatically created for you
}

您的发票模型将如下所示:

attributes: {
name: "STRING"
items: {
collection: "item",
via: "item"
}
}

现在创建一些 item 模型的文档。

sails> ModelNameOfItem.create({name:'MyFirstItem'}).exec(console.log)
null { name: 'MyFirstItem',
createdAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST),
updatedAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST),
_id: "some_id_created_by_mongo" }

现在创建一个invoice 模型的文档。

sails> ModelNameOfInvoice.create({name:'MyFirstInvoice', items:"the_id from_item_created"}).exec(console.log)
null { name: 'MyFirstInvoice',
createdAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST),
updatedAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST),
_id: "some_id_created_by_mongo" }

就是这样!要查询它,请使用 populate 方法。

sails> Invoice.find({name:'MyFirstInvoice'}).populate('items').exec(console.log);

关于javascript - Sails.js:如何使用模型关联填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23190988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com