Sails.js中两个模型的关联

Associations of two Models in Sails.js

本文关键字:两个 模型 关联 js Sails      更新时间:2023-09-26

我遇到了帆船中两个模型的链接问题。我有两个模特:歌手和乡村。在'Singer'模型中,我有一个属性'singer_country',它表示'Country'模型的id。我的问题是,当我显示所有歌手的属性时,我可以在'Country'模型中获得属性'country_name'。我不知道怎么做。下面是我的代码:我的"歌手"模型

 module.exports = {
attributes: {
singer_name:{
    type: 'string',
    required: true,
    size: 50
},
singer_realname:{
    type: 'string',
    size: 50
},
singer_gender:{
    type: 'string',
    enum: ['Male', 'Female'],
    defaultsTo: 'Male'
},
singer_brithday:{
    type: 'int'
},
singer_image:{
    type: 'string'
},
singer_description:{
    type: 'string'
},
singer_country:{
    type: 'string'
}
}
};

我的"国家"模型:

  module.exports = {
attributes: {
country_name: {
    type: 'string'  
}
}
};

显示歌手属性的方法:

index: function(req, res, next){
    Singer.find().exec(function foundSinger(err, singerObj){
        if(err) return next(err);   
            res.view({
                singers: singerObj,
        });     
    });
},

我的数据库是MongoDB,我使用的是风帆beta 0.10 rc8。谢谢你的帮助。

singer_country:{
    model: 'Country'
}
Singer.find().populate('singer_country').exec(function foundSinger(err, singerObj){
    if(err) return next(err);   
        res.view({
            singers: singerObj,
    });     
});

这里还有很多其他的变量,但是如果你的关联是一对一的那么你的singer_country属性就需要像

这样
singer_country: {model: 'country'}
https://github.com/balderdashy/waterline-docs/blob/master/associations.md