sequelize查询执行中属性中的“hasmany”关联(模型)计数

vawmfj5a  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(656)

sequelize版本:4.22.6,mysqlversion:5.7.8 i 要在查询执行中的attibutes(在\u user\u count\u处)中进行“hasmany”关联(companyuser)计数吗

/**

* Company user associate with Company with belongsTo relation
* /

`CompanyUser.belongsTo(Company, { foreignKey: 'company_id', targetKey: 'id'});`

/**

* Company  associate with Company user with hasMany relation
* /

`Company.hasMany(CompanyUser, { foreignKey: 'company_id', sourceKey: 'id'});`

`return Company.findAll({
    attributes: [
        'id', 'title', 'is_enabled', '_user_count_'
    ]
    include: [
        {
            model: sqConn.CompanyUser,
            attributes: ['id'],
        },
        {
            model: sqConn.CompanyLogo,
            attributes:['file_object'],
        }
    ],
}).then(function(model) {
    return sequelize.Promise.resolve(model);
}).catch(function(err) {
    return sequelize.Promise.reject(err);
});`

使用左连接的简单mysql查询可以很好地工作并给出计数。

lvmkulzt

lvmkulzt1#

你可以用 sequelize.fn ,尝试运行以下查询:

Company.findAll({
    attributes: [
        'id', 'title', 'is_enabled',
        [sequelize.fn('count', sequelize.col('company_users.id')) ,'user_count'] // <---- Here you will get the total count of user
    ],
    include: [
        {
            model: sqConn.CompanyUser,
            attributes: [] // <----- Make sure , this should be empty
        }
    ],
    group: ['companies.id'] // <---- You might require this one also
}).then(data => { 
    console.log(data); // <---- Check the output
})
7jmck4yq

7jmck4yq2#

这对我很有用:

await PostModel.findAll({
  group: ['posts.id'],
  order: [['createdAt', 'DESC']],
  include: [
    {
      model: CategoryModel,
      attributes: ['title'],
      where: { title: categoryTitle }
    },
    { model: CommentModel },
    { model: UserModel, attributes: ['fullname', 'id'] }
  ],
  attributes: [
    'title', 'content', 'description', 'thumbnail', 'baner', 'createdAt', 'updatedAt',
    [Sequelize.fn('COUNT', 'comment.id'), 'commentsCounter']
  ]
});

关联:
后m:n类别
帖子1:n评论
post n:1个用户
请注意这部分 'comment.id' 不是 'comments.id' .
如果你使用 'comments.id' 它会为您抛出以下错误: SequelizeDatabaseError: missing FROM-clause entry for table "comments" 我的模型-更新:

和评论

const { sequelize } = require('./index');
const { Model, DataTypes } = require('sequelize');
class CommentModel extends Model {};
CommentModel.init({
    id: {
        primaryKey: true,
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4
    },
    content: {
        type: DataTypes.TEXT,
        allowNull: false
    }
}, {
    sequelize,
    modelName: 'comments',
    timestamps: true,
    paranoid: false
});

module.exports = CommentModel;

相关问题