sequelize js count结果集模型关联

时间:2016-11-23 08:20:55

标签: node.js instance sequelize.js getter-setter class-method

我有三个模特

  1. postTag
  2. 标签
  3. 我只想在获取postTag时添加标记计数。 这是我的getPost函数

    
    
    models.post.findAll({
      include: [
        {
          model: models.postTag,
          //include:[{model:models.tag}],
          //attributes: [[models.sequelize.fn('count', models.sequelize.col('postTags.post_id')), 'count']]
        }
      ],
        where: postData.where
    })
    
    
    
 这是我的PostTag模型

    
    
    var models = require('../models');
    module.exports = function (sequelize, DataTypes) {
      return sequelize.define('postTag',
        {
          post_id: {
              type:DataTypes.INTEGER,
              primaryKey: true
          },
          tag_id: {
              type:DataTypes.INTEGER,
              primaryKey: true
          },
          order_no: DataTypes.INTEGER,
          create_time: DataTypes.DATE,
        },
        {
          timestamps: false,
          underscored: true,
          freezeTableName: true,
          tableName : 't_post_tag',
          classMethods:
            {
              associate: function (models) {
              models.postTag.belongsTo(models.post,{  foreignKey :"post_id", targetKey:"post_id" });
              //models.postTag.belongsTo(models.tag,{  foreignKey :"tag_id", targetKey:"tag_id" });
            }
            },
            instanceMethods: {
              tag_name: function () {
                  return models.tag.findById(this.getDataValue('tag_id'));
              },
              count: function(){
                // please  complete this
              }
            },
            getterMethods: {
                // tag_name: function () {
                //     return models.tag.findById(this.getDataValue('tag_id'));
                // }
            },
            setterMethods: {
    
            }
        }
        );
      }
    </code></pre>
    
    Now i'm gtting this response
    <pre><code>
    {
      "status": true,
      "response": [
        {
          "create_time": "Tue Nov 22 2016",
          "post_id": "38",
          "description": "good palce",
          "create_by": 67,
          "update_time": "2016-11-22T15:32:22.985Z",
          "country_id": 156,
          "postTags": [
            {
              "post_id": 38,
              "tag_id": 8,
              "order_no": 1,
              "create_time": "2016-11-21T18:30:00.000Z",
              "tag": {
                "tag_id": 8,
                "tag_name": "Hiking",
                "tag_type": "Travel Activity",
                "create_time": "2016-09-23T06:12:00.000Z"
              }
            }
          ]
        }
      ]
    }
    &#13;
    &#13;
    &#13; 这是两个问题

    1. 我没有在postTag阵列中获得计数键
    2. 任何人都可以告诉方法在 postTag 数组中获取tag_name而不是包含整个数组标记数组请参阅响应
    3. 我厌倦了在instanceMethod中付出努力,请参阅模型。请救救我

0 个答案:

没有答案