在sailsjs.org的文档中,拥有方的一对多关系定义如下
//user.js
module.exports = {
attributes: {
name:'STRING',
age:'INTEGER',
pets:{
collection: 'pet',
via: 'owner'
}
}
}
“宠物”是一个常量,在SQL数据库上具有一致的架构。如果我想拥有一个具有唯一属性(不同行数)的超类宠物和子类,该怎么办?说我有一只章鱼和一只狗。狗有四条腿和两只耳朵。章鱼有8只触须。唯一的共性将被抽象为宠物类(颜色、姓名、年龄)。
如果这不可能的话,我就不得不求助于这样的事情了,不是吗?
//user.js
module.exports = {
attributes: {
name:'STRING',
age:'INTEGER',
dogs:{
collection: 'dog',
via: 'owner'
},
octopuses:{
collection: 'octopus',
via: 'owner'
}
}
}
但是,如果我想引入更多的宠物,比如鹰(会飞)、鹦鹉(会说话),这可能会变得非常混乱,如果我使用SQL数据库,将会导致很多空值。也许mongoDB是这方面的理想选择?
发布于 2014-08-20 22:22:41
在Waterline中,每个模型都被视为SQL数据库中的表或Mongo中的集合。如果狗与八达通有完全不同的属性,那么是的,你可以将它们分解成不同的表,并将它们链接到用户。我认为最简单的方法就是将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
}]
https://stackoverflow.com/questions/25397136
复制相似问题