Javascript Sequelize Association获取计数,无需查询
我有这两种型号:Javascript Sequelize Association获取计数,无需查询,javascript,node.js,postgresql,sequelize.js,Javascript,Node.js,Postgresql,Sequelize.js,我有这两种型号: module.exports = { /* funcao que numa fase beta vai obter fotos completamente random para demonstração, mas que mais tarde vai ser responsável por verificar através dos pixeis a sua similiaridade*/ allSpeciesForGenre: functio
module.exports = {
/* funcao que numa fase beta vai obter fotos completamente random para demonstração, mas que mais tarde vai ser
responsável por verificar através dos pixeis a sua similiaridade*/
allSpeciesForGenre: function (req, res, next) {
/*order: [
Sequelize.fn('RAND'),
]*/
Plant.findAll({
where: {
genreId: req.params.id,
include: 'species'
}
})
.then(function (plants) {
if (JSON.stringify(plants) == "[]") {
return res.status(204).send({ message: "Ainda não existem espécies disponíveis!" })
}
console.log(plants);
return res.send(plants);
}).catch(function (err) {
console.log(err.stack);
return res.status(400).send({ message: err.stack }); //
})
}
}
流派
module.exports = function (sequelize, DataTypes) {
var Genre = sequelize.define("Genre", {
name: {
type: DataTypes.STRING,
allowNull: false
},
familyId: {
type: DataTypes.INTEGER,
allowNull: true
}
},
{
associate: function (models) {
Genre.hasMany(models.Plant, { foreignKey: "genreId", as: 'plant' });
}
}
);
**Plant**
module.exports = function (sequelize, DataTypes) {
var Plant = sequelize.define("Plant", {
specie: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.TEXT,
allowNull: true,
defaultValue: "No description for this plant yet"
},
directory: {
type: DataTypes.STRING,
allowNull: false
},
genreId: {
type: DataTypes.INTEGER,
allowNull: true
}
},
{
associate: function (models) {
Plant.hasMany(models.Foto, { foreignKey: "plantId", as: 'fotos' });
}
}
);
一种植物只能有一种类型,但一种类型可以与许多植物相关联,因此在我的客户应用程序中,我有一棵树,我点击一个家族,它会显示很多类型,我点击一种类型,它会显示所有植物
我需要的是:例如,当我输入families时,我想显示每个流派拥有的植物数量,因此我需要知道我的流派中植物的长度,此时我可以在流派视图中获取与流派相关的数据
所以我做这个查询:
module.exports = {
/* funcao que numa fase beta vai obter fotos completamente random para demonstração, mas que mais tarde vai ser
responsável por verificar através dos pixeis a sua similiaridade*/
allSpeciesForGenre: function (req, res, next) {
/*order: [
Sequelize.fn('RAND'),
]*/
Plant.findAll({
where: {
genreId: req.params.id,
include: 'species'
}
})
.then(function (plants) {
if (JSON.stringify(plants) == "[]") {
return res.status(204).send({ message: "Ainda não existem espécies disponíveis!" })
}
console.log(plants);
return res.send(plants);
}).catch(function (err) {
console.log(err.stack);
return res.status(400).send({ message: err.stack }); //
})
}
}
我把特殊的包含放在那里,这样我可以得到所有的植物,但它不起作用,我需要得到这个查询中植物数量的计数
谢谢如果需要获得行数,只需使用
count()
函数Plant.count({where:{genreId:req.params.id}})
我可以将其添加到返回实例吗?因为目前我正在返回模型