我正在使用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));
};