[V5] how to get values from ManyToMany relationship? #1768
-
I'm trying to make a seeder to test my API. I want to create a Company along with its Branch, and I've created something like this in for the seeder: // somewhere inside Role.ts
@manyToMany(() => User)
public users: ManyToMany<typeof User>
// CompanySeeder.ts
export default class CompanySeeder extends BaseSeeder {
public static developmentOnly = true
public async run () {
const rcl = await Role.findByOrFail('name', 'c-level')
for (const user of rcl.users) {
const companies = await CompanyFactory.merge({ userId: user.id }).createMany(5)
for (const company of companies) {
await BranchFactory.merge({ companyId: company.id }).createMany(5)
}
}
}
} But the console give me an error: |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
the preload method does not return the users array, it just preloads the data. await rcl.preload('users'); and after that, on your next line you should have access to your users array to iterate over it |
Beta Was this translation helpful? Give feedback.
-
You can also do: const users = await rcl.related('users').query().fetch() |
Beta Was this translation helpful? Give feedback.
the preload method does not return the users array, it just preloads the data.
so, in your example you should be able to do
and after that, on your next line you should have access to your users array to iterate over it