Wednesday 31 May 2017

Sequelize assocation get count without query

I have this two models:

Genre

    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' });
      }
    }
  );

a plant can have just 1 genre, but 1 genre can be associate to many plants, so in my client aplication i have something like a tree, i click in 1 family it show me a lot of genres, i click on 1 genre it show me all plants.

What i need is: when i enter for example in families, i want to show the number of plants that each genre has, so i need somehow to know the length of the plants inside my genre, at the moment i can just get the data associated with the genre inside the genre view.

So i do this query:

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 }); // 
            })
    }

}

i put the special include there, so i can get all plants but it doesn't work i need to get the count of number of plants inside this query,

Thank you



via Filipe Costa

No comments:

Post a Comment