factory-girl icon indicating copy to clipboard operation
factory-girl copied to clipboard

How to define @many to many ?

Open crixusshen opened this issue 6 years ago • 1 comments

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

crixusshen avatar Nov 19 '18 08:11 crixusshen

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] })

tomaszgiba avatar May 10 '19 12:05 tomaszgiba