Sequelize не создает методы set / get / add - PullRequest
1 голос
/ 12 января 2020

Я не уверен, что что-то упустил, но, похоже, Sequelize не создает методы, производные от ассоциаций ownToMany (...) (в данном случае: setRequest, getRequest, addRequest Sequelize Docs )

Я пытаюсь создать отношение N: N (с едой и запросами). Таким образом, запрос может иметь много продуктов , а продукт может иметь запросов

Ошибка:

(узел: 4504) UnhandledPromiseRejectionWarning: TypeError: food.addRequests не является функцией

Models

Модель запроса:

const { Model, DataTypes } = require('sequelize');

class Request extends Model {
  static init(sequelize) {
    super.init({
      //Format
      client: DataTypes.STRING(70),
      time_processing: DataTypes.INTEGER,
      time_cooking: DataTypes.INTEGER,
      time_paying: DataTypes.INTEGER,
      //Has one Table
    }, {
      //Conection
      sequelize
    })
  }

  static associate(models) {
    this.belongsTo(models.Table, { foreignKey: 'fk_table', as: 'table', targetKey: 'id' });
    this.belongsTo(models.Employee, { foreignKey: 'fk_employee', as: '' });
    this.belongsToMany(models.Food, { foreignKey: 'fk_request', through: 'requests_foods', as: 'request' });
  }
}

module.exports = Request;

Модель еды:

const { Model, DataTypes } = require('sequelize');

class Food extends Model {
  static init(sequelize) {
    super.init({
      //Format
      name: DataTypes.STRING(40),
      image: DataTypes.STRING,
      price: DataTypes.FLOAT,
      storage: DataTypes.INTEGER,
      //Is used By Many Requests
    }, {
      //Conection
      sequelize,
      tableName: 'foods'
    })
  }

  static associate(models) {
    //Through: Table used to join data
    //foreignKey: Which column of requests_foods is used to reference to models.Request
    this.belongsToMany(models.Request, { foreignKey: 'fk_food', through: 'requests_foods', as: 'foods' });
    this.belongsTo(models.Category, { foreignKey: 'fk_category', as: 'category' });
  }
}

module.exports = Food;

Сводная таблица:

'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('requests_foods', {
      id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true,
        allowNull: false,
      },
      fk_request: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'requests', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      fk_food: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'foods', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'RESTRICT'
      },
      ammount: {
        type: Sequelize.INTEGER,
        allowNull: false,
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
      }
    });
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('requests_foods');
  }
};

И, наконец, контроллер (где выдается ошибка)

const Request = require('../models/Request');
const Food = require('../models/Food');

module.exports = {
  async list(req, res) {
    const dbResponse = await Request.findAll();
    return res.json(dbResponse);
  },

  async add(req, res) {
    const { client, time_processing, time_cooking, time_paying, fk_table, fk_employee, foods } = req.body;
    console.log(req.body);

    const dbResponse = await Request.create({ client, time_processing, time_cooking, time_paying, fk_table, fk_employee });

    //Look for food list
    foods.map(async item => {
      console.log('ITEM:', item);
      const food = await Food.findByPk(item.fk_food)

      console.log(food);
      food.addRequests(); //ERROR HERE
    })

    return res.json(dbResponse);
  }
}

Примечания:

  1. запрос добавлен, но request_foods нет.

  2. Я попытался изменить на: addRequest (), setRequests, setRequest (), но ничего не работает, я console.log объекта, и кажется, что у объекта просто нет никакого метода:

{ client: 'Wesley Almeida Braga',
  time_processing: 0,
  time_cooking: 0,
  time_paying: 0,
  fk_table: 1,
  fk_employee: 1,
  foods: [ { fk_food: 1 } ] }
Executing (default): INSERT INTO `requests` (`id`,`client`,`time_processing`,`time_cooking`,`time_paying`,`created_at`,`updated_at`,`fk_employee`,`fk_table`) VALUES (DEFAULT,?,?,?,?,?,?,?,?);
ITEM: { fk_food: 1 }
Executing (default): SELECT `id`, `name`, `image`, `price`, `storage`, `created_at` AS `createdAt`, `updated_at` AS `updatedAt`, `fk_category` FROM `foods` AS `Food` WHERE `Food`.`id` = 1;
Food {
  dataValues:
   { id: 1,
     name: 'Carne de Sol',
     image: 'example_2.png',
     price: 25,
     storage: 10,
     createdAt: 2020-01-12T03:48:34.000Z,
     updatedAt: 2020-01-12T03:48:34.000Z,
     fk_category: 1 },
  _previousDataValues:
   { id: 1,
     name: 'Carne de Sol',
     image: 'example_2.png',
     price: 25,
     storage: 10,
     createdAt: 2020-01-12T03:48:34.000Z,
     updatedAt: 2020-01-12T03:48:34.000Z,
     fk_category: 1 },
  _changed: {},
  _modelOptions:
   { timestamps: true,
     validate: {},
     freezeTableName: false,
     underscored: true,
     paranoid: false,
     rejectOnEmpty: false,
     whereCollection: { id: 1 },
     schema: null,
     schemaDelimiter: '',
     defaultScope: {},
     scopes: {},
     indexes: [],
     name: { plural: 'Food', singular: 'Food' },
     omitNull: false,
     sequelize:
      Sequelize {
        options: [Object],
        config: [Object],
        dialect: [MysqlDialect],
        queryInterface: [QueryInterface],
        models: [Object],
        modelManager: [ModelManager],
        connectionManager: [ConnectionManager],
        importCache: {} },
     tableName: 'foods',
     hooks: {} },
  _options:
   { isNewRecord: false,
     _schema: null,
     _schemaDelimiter: '',
     raw: true,
     attributes:
      [ 'id',
        'name',
        'image',
        'price',
        'storage',
        'createdAt',
        'updatedAt',
        'fk_category' ] },
  isNewRecord: false }
...