I have three tables:
id | name |
---|---|
1 | name1 |
2 | name2 |
id | |
---|---|
1 | email@1 |
2 | email@2 |
user_id | campaign_id | class_id |
---|---|---|
1 | 4 | 1 |
2 | 4 | 2 |
I need to make a call in MYSQL that finds the user that belongs to the campaign and the class that has the rule equal to 4 (which is in the campaign_user table) and attach his email to the class How do you do it in Adonis?
I expect to get back:
[{id:1,name:name1,email:email@1 },{id:2,name:name2,email:email@2 }]
id - Belongs to class.
name - Belongs to class.
email - Belongs to user.
I found a solution:
in Models/class.ts
@manyToMany(() => User, {
pivotTable: 'campaign_user',
localKey: 'id',
relatedKey: 'id',
pivotForeignKey: 'class_id',
pivotRelatedForeignKey: 'user_id',
onQuery(query) {
query.where('campaign_user.role', 4).select('email', 'phone', 'username')
},
})
public managerDetails: ManyToMany<typeof User>
in campaign model:
@hasMany(() => Class)
public classes: HasMany<typeof Class>
And when I use it then I created the function:
public async classesIndex(): Promise<Class[]> {
const c: Campaign = this
await c.load('classes')
for (let i = 0; i < c.classes.length; i++) {
await c.classes[i].load('managerDetails')
}
return c.classes
}