user.hasMany(Product) 关联会将以下方法添加到User 模型中。
/**
* The addAssociations mixin applied to models with hasMany.
* An example of usage is as follows:
*
* ```js
*
* User.hasMany(Role);
*
* interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
* // getRoles...
* // setRoles...
* addRoles: Sequelize.HasManyAddAssociationsMixin<RoleInstance, RoleId>;
* // addRole...
* // createRole...
* // removeRole...
* // removeRoles...
* // hasRole...
* // hasRoles...
* // countRoles...
* }
* ```
*
* @see https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html
* @see Instance
*/
对于您的情况,您应该使用userModel.addProducts(productModels)。例如
import { sequelize } from '../../db';
import { Model, DataTypes, HasManyAddAssociationsMixin } from 'sequelize';
class User extends Model {
public addProducts!: HasManyAddAssociationsMixin<Product, number>;
}
User.init(
{
email: {
type: DataTypes.STRING,
unique: true,
},
},
{ sequelize, modelName: 'users' },
);
class Product extends Model {}
Product.init(
{
name: DataTypes.STRING,
},
{ sequelize, modelName: 'products' },
);
User.hasMany(Product);
Product.belongsTo(User);
(async function test() {
try {
await sequelize.sync({ force: true });
// seed
await User.create(
{
email: 'example@gmail.com',
products: [{ name: 'apple' }, { name: 'amd' }],
},
{ include: [Product] },
);
// add another two products for this user
const SomeID = 1;
const productobj = [{ name: 'nvidia' }, { name: 'intel' }];
const productModels = await Product.bulkCreate(productobj);
const userObj = await User.findOne({ where: { id: SomeID } });
await userObj.addProducts(productModels);
} catch (error) {
console.log(error);
} finally {
await sequelize.close();
}
})();
数据库中的数据行:
=# select * from users;
id | email
----+-------------------
1 | example@gmail.com
(1 row)
node-sequelize-examples=# select * from products;
id | name | userId
----+--------+--------
1 | apple | 1
2 | amd | 1
3 | nvidia | 1
4 | intel | 1
(4 rows)
注意:这些方法只接受目标模型作为参数,不是一个普通的 javascript 对象或对象数组。您需要bulkCreate 产品。然后,使用userModel.addProducts(productModels) 将这些产品与该用户关联