sailsjs

时间:2015-06-29 18:33:17

标签: model sails.js

我目前正在Sails.js应用程序中设置我的模型,并且想知道是否有可能很好地解决我的小问题:

所以我想表达以下关系:
文档具有内容,可以是(模型)类型A或类型B. 有没有办法在不将A型和B型合并为一个大型模型或在文档模型中为每种类型添加一个属性的情况下表达这一点? 对于模型而言可能类似于enums,而对于字符串则不是(如果可能的话)。

或者我是否必须通过以下唯一ID进行查找:

    
// model Document
module.exports = {

    contentType: {
        type: 'string',
        required: true,
        enum: ['typeA', 'typeB'],
    },
    contentID: {
       type: 'integer',
       required: true
    },
}

// model typeA
module.exports = {

    id: {
        type: 'integer',
        autoIncrement: true
    },
    heading: {
       type: 'string',
       required: true
    },
    body: {
       type: 'string',
       required: true
    },
}

理想情况下,我只想写:

// model Document
module.exports = {

    contentType: {
        model: ['typeA', 'typeB'],
    },
}

或类似的东西(如果可能的话)。

2 个答案:

答案 0 :(得分:1)

AFAIK无需任何应用程序逻辑即可完成。因为SQL(也就是Sails / Waterline关系)模型是使用table-to-table关系。您的关系record-to-record可用于NoSQL graph db,例如Neo4j,TitanDB等,当然Waterline(目前)仍然无法集成它。

答案 1 :(得分:1)

目前无法做到这一点,而您目前正在使用的方法是我在放弃多属性方法后最终确定的方法(可行,但对管理非常恼火)。 / p>

但是,如果您的模型(typeA和typeB)很轻,并且您希望将它们存储在同一属性下,则可以声明custom validation,如下所示:

//model Document
function isTypeA(content) {
    //check if content is a valid typeA object
}
function isTypeB(content) {
    //check if content is a valid typeB object
}
module.exports = {
    types: {
        typeAOrTypeB: function(content){
            return isTypeA(content) || isTypeB(content);
        }
    },
    attributes: {
        contentType: {
            type: 'string',
            enum: ['typeA', 'typeB']
        },
        content: {
            type: 'json',
            typeAOrTypeB: true
        }
    }
}

(如果content甚至适度详细,我仍然更喜欢多模型方法。)