【问题标题】:Associations of two Models in Sails.jsSails.js 中两个模型的关联
【发布时间】:2014-07-03 04:13:13
【问题描述】:

我在帆中连接两个模型时遇到了麻烦。我有两个模特“歌手”和“乡村”。在“歌手”模型中,我有一个属性“singer_country”,表示“国家”模型的 id。我的问题是当我显示所有歌手的属性时,我可以在“国家”模型中获得属性“国家名称”。我不知道怎么做。下面是我的代码: 我的“歌手”模特

 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,我使用的是sails beta 0.10 rc8。感谢您的帮助。

【问题讨论】:

    标签: javascript mongodb sails.js ejs


    【解决方案1】:
    singer_country:{
        model: 'Country'
    }
    
    Singer.find().populate('singer_country').exec(function foundSinger(err, singerObj){
        if(err) return next(err);   
            res.view({
                singers: singerObj,
        });     
    });
    

    【讨论】:

    • 返回错误:“TypeError: Object [object Object] has no method 'populate'”
    【解决方案2】:

    这里还有很多其他变量,但如果您的关联是一对一的,那么您的 Singer_country 属性需要类似于

    singer_country: {model: 'country'}
    

    https://github.com/balderdashy/waterline-docs/blob/master/associations.md

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 2021-09-28
      • 2014-04-27
      • 2016-01-11
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      相关资源
      最近更新 更多