sequelize在“包含”模型数组上返回未定义的

时间:2019-10-26 06:38:08

标签: mysql node.js express sequelize.js

我正在使用sequelize版本:5.21.1,并且具有以下模型。

@if ($errors->any())
  <div class="alert alert-danger">
    <ul>
        @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
        @endforeach
    </ul>
  </div>
@endif

和关联是

const User = sequelize.define('user', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false
  },
  email: {
    type: Sequelize.STRING,
    allowNull: false
  }
});

module.exports = User;
-------------------------------------------

const Order = sequelize.define('order', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
  },
  quantity: Sequelize.INTEGER
});

module.exports = Order;

-----------------------------------------


const OrderItem = sequelize.define('orderItem', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
  },
  quantity: Sequelize.INTEGER
});

module.exports = OrderItem;
------------------------------------

const Product = sequelize.define('product', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
  },
  title: {
    type: Sequelize.STRING,
    allowNull: false
  },
  price: {
    type: Sequelize.DOUBLE,
    allowNull: false
  },
  imageUrl: {
    type: Sequelize.STRING,
    allowNull: false
  },
  description: {
    type: Sequelize.STRING,
    allowNull: false
  }
});

module.exports = Product;

但是下面的代码返回一个未定义的对象。我可以在结果中看到类型为“ Array”的属性“ products”,但是当我记录该属性时,它显示为未定义。

Product.belongsTo(User, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(Product);
Order.belongsTo(User);
User.hasMany(Order);
Order.belongsToMany(Product, { through: OrderItem });

生成的查询工作正常,我可以在DB(mysql)中看到结果。

exports.getOrders = (req, res, next) => {
  req.user
    .getOrders({ include: [ {model: Product} ] })
    .then(orders => {
      console.log(orders); //result has property 'products'
      console.log(orders.products);//result is undefined
      orders.products.forEach(element => {//Cannot read property 'forEach' of undefined
        console.log(element);
      });

    })
    .catch(err => console.log(err));
};

0 个答案:

没有答案