gpt4 book ai didi

javascript - sails.js 一对多关系——变量所有者集合属性

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:08 25 4
gpt4 key购买 nike

在 sailsjs.org 的文档中,拥有方的一对多关系是这样定义的

//user.js
module.exports = {
attributes: {
name:'STRING',
age:'INTEGER',
pets:{
collection: 'pet',
via: 'owner'
}
}
}

'pet' 是一个常量,在 SQL 数据库上具有一致的架构。如果我想要一个父类(super class)宠物和具有独特属性(不同行数)的子类怎么办?假设我有一只 Octopus 和一只狗。狗有4条腿和2只耳朵。 Octopus 有 8 条触手。唯一的共性将被抽象为宠物类(颜色、名字、年龄)。

如果这是不可能的,我将不得不采取这样的方法,不是吗?

//user.js
module.exports = {
attributes: {
name:'STRING',
age:'INTEGER',
dogs:{
collection: 'dog',
via: 'owner'
},
octopuses:{
collection: 'octopus',
via: 'owner'
}
}
}

但是,如果我想引入更多的宠物,例如鹰(会飞)、鹦鹉(会说话),这可能会变得非常困惑,并且如果我要使用 SQL 数据库,则会导致许多空值。也许 mongoDB 是理想的选择?

最佳答案

在 Waterline 中,每个模型都被视为 SQL 数据库中的表或 Mongo 中的集合。如果狗与 Octopus 具有完全不同的属性,那么是的,您可以将它们分成单独的表并将它们链接到用户。我认为最简单的方法就是向 Pet 模型添加 type 属性。

// user.js
module.exports = {
attributes: {
name:'STRING',
age:'INTEGER',
pets:{
collection: 'pet',
via: 'owner'
}
}
}

// pet.js
module.exports = {
attributes: {
name:'STRING',
type: 'STRING',
owner:{
model: 'user'
}
}
}

这将允许查询,例如:

User.find().populate('pets', { type: 'dog' });

另一种选择是将宠物属性存储在 json 对象中。目前无法搜索,但允许您以非规范化的方式存储有关宠物的各种信息。

// pet.js
module.exports = {
attributes: {
name:'STRING',
type: 'STRING',
characteristics: {
type: 'json'
},
owner:{
model: 'user'
}
}
}

这将允许你拥有如下所示的宠物:

[{
id: 1,
name: 'fluffy',
type: 'dog',
characteristics: {
food: 'mice',
limbs: 4,
fur: 'white'
},
owner: 1
},
{
id: 2,
name: 'inky',
type: 'octopus',
characteristics: {
habitat: 'ocean'
tentacles: 8,
canChooseWorldCupWinners: true
},
owner: 1
}]

关于javascript - sails.js 一对多关系——变量所有者集合属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25397136/

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