Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to define @many to many ? #144

Open
crixusshen opened this issue Nov 19, 2018 · 1 comment
Open

How to define @many to many ? #144

crixusshen opened this issue Nov 19, 2018 · 1 comment

Comments

@crixusshen
Copy link

crixusshen commented Nov 19, 2018

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

@tomaszgiba
Copy link

tomaszgiba commented May 10, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants