Tuesday 30 May 2017

Add data two tables Sequelize

Here its my problem.

I create a Api rest in nodejs where i manage my database. I have 3 tables: bets, users and users-bets (this one link bets with users).

Well my problem is when im using Sequelize to do this. In my webpage, its an Angular2 app, i want to create a new bet so when i fill the formulary i send all the data to the server by post method. The problem start here because i want to add in the bets table (thats not the problem) and add the reference in bets-users.

Example:

User A create a new bet, so when he click on create, he send a post method with the bet data that contains Title, cost and earnings. In the server side, the query runs fine but what i want it is that when i insert the bet in the bet table, i want to add the id_bet and the id_user in bet-users because i want to link the user that adds the bet with the bet that he create.

I dont know if im explaining good.

Here its my code:

This is the bets model.

module.exports = (sequelize, Sequelize) => {
  const Bet = sequelize.define('apuestas', {
    id: {
      type: Sequelize.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    titulo: {
      type: Sequelize.STRING
    },
     coste: Sequelize.INTEGER,
     beneficio: Sequelize.INTEGER
  }, {
    updatedAt: false,
    classMethods: {
      associate: (models) => {
      Bet.belongsTo(models['usuarios_apuestas'], {
          foreignKey: 'id',
           targetKey: 'id_apuesta'
       });
      }
    },
    freezeTableName: true
  });

  return Bet;
};

I have a controller:

createBet(req, res) {
        return this.service.create(this.mapper.inputUpdate(req.body))
        .then(this.mapper.outputGet.bind(this.mapper, req.body))
        .then(res.json.bind(res)).catch(res.send.bind(res));
      }

This is the mapper:

inputUpdate(inputBet) {
    return  {
      titulo: inputBet.titulo,
      coste: inputBet.coste,
      beneficio: inputBet.beneficio
    };
  }

And the service:

create(model) {
    return this.db.create(model);
  }

All this methods are separate in different files.

In summary, what i want its that when i add a new bet i want to add in the bet-users the relation between users and bets saving his id.

The bets-user table have 3 columns: id, id_bet, id_user.

Now i can find all bets in that an user participate using his id_user.

I dont know if i need to explain more my problem or if you dont understand it.

titulo = title
coste = cost
beneficio = earnings



via Tibo

No comments:

Post a Comment