factory-girl
factory-girl copied to clipboard
How to define @many to many ?
I currently have a user table, a role table, and the relationship between users and roles is many-to-many, so there is a middle table of user_role. How to configure it
user table: id | name | age
role table: id | name
user_role table: user_id | role_id
You have to do this manually. It doesn't seem that this factory-girl supports N:N relationships.
It depends on your db adapter, but with Sequelize I'm doing this:
factory.define('User', models.User, {
name: 'Test User'
}, {
afterCreate: async (model, attrs, _buildOptions) => {
if (!attrs.roles) return model
await model.addRoles(attrs.roles) // given, that you have assoc. defined with Sequelize
return model
}
})
const role = factory.create('Role')
const user = factory.create('User', { roles: [role] })