简体   繁体   中英

How do I access records in node.js using 'has-many belongs-to relationaship'?

I am new to node.js. I am using sequelize in my app. I have the following models:

var Topic = sequelize.define('Topic', {
  topic_name: Sequelize.STRING,
  topic_category: Sequelize.STRING
},{tableName: 'Topics'})

var RawStatistic = sequelize.define('RawStatistic', {
  feedback_value: Sequelize.STRING,
  count: Sequelize.INTEGER,
  total_feedbacks_for_this_topic: Sequelize.INTEGER
},{tableName: 'RawStatistics'})

And the rellation between them as follows:

RawStatistic.belongsTo(Topic);
Topic.hasMany(RawStatistic);

But when I use:

    RawStatistic.all({limit: FIVE}).success(function (raw_statistics) {
    raw_statistics.getTopic().success(function (r){
    res.json(r)
    });
  });

I get the error:

TypeError: Object [object Object] has no method 'getTopic'

My question is how do I access a particular Topic name if I have a Feedback record? What is the syntax for the same? Probably I am overlooking an obvious syntax to achieve this. Any help would be much appreciated. Thanks in advance:)

You're trying to use an instance method on a collection of instances. You need to iterate over the result:

RawStatistic.all({limit: FIVE}).success(function (raw_statistics) {
  var i;
  for(i = 0; i < raw_statistics.length; ++i){
    raw_statistics[i].getTopic().success(function (t){
      /* ... */
    });
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM