sails.js一对多的关系 – variables所有者集合属性

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

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

“pet”是一个常量,在SQL数据库上有一致的模式。 如果我想拥有一个超类宠物和具有独特属性(不同行数)的子类呢? 说我有一只章鱼和一只狗。 狗有4条腿和2个耳朵。 章鱼有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中的Collection。 如果一只狗与八达通的属性完全不同,那么你可以将它们分成不同的表格并链接到用户。 我认为最简单的方法只是将一个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' }); 

另一种select是将宠物属性存储在json对象中。 这目前不可search,但将允许您以非规范化的方式存储关于宠物的各种事情。

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