I'm currently playing around with AdonisJS v5 and I'm having a bit of an issue with ManyToMany relationships.
I have the current 2 models
User
export default class User extends BaseModel {
@column({ isPrimary: true })
public id: Buffer;
...
@manyToMany(() => Family)
public families: ManyToMany<typeof Family>;
}
Family
export default class Family extends BaseModel {
@column({
isPrimary: true,
})
public id: Buffer;
@column({
serializeAs: null,
})
public UserId: Buffer;
public name: string;
@manyToMany(() => User)
public users: ManyToMany<typeof User>;
}
I then have a pivot table FamilyToUser
with a basic structure of a UserId and a FamilyId.
I am then finding the User by email as follows
const user = await User.findBy(
'email',
'[email protected]'
);
I then try load the ManyToMany relationship using await user.load('families');
Now, when I loop through the families and output everything, it's not pulling the columns in the model as I would have thought. If I do the follow
await user.load('families', (familyQuery) => {
familyQuery.whereNull('deleted');
});
const familiesJson = user.families.map((family) => family.serialize());
console.log(familiesJson);
I'll get a printout as follows
[ { Id: 'fc7ffd40-298c-11ed-ad7e-759bb78c2a4c' } ]
As you can see, it returns only the Id
column, not the name
column. Now, if print out the family as follows
user.families.forEach((family) => {
console.log(family);
});
I get the following printout
Family {
...
'$extras': {
name: 'Surname',
pivot_Userid: <Buffer 11 ed 29 8a fa 64 f7 60 98 47 89 c2 78 79 62 24>,
pivot_Familyid: <Buffer 11 ed 29 8c fc 7f fd 40 ad 7e 75 9b b7 8c 2a 4c>
},
...
}
Where it's printing out the columns and the pivot table Fks into the $extras property. Looking at the docs found here, this property should only contain the pivot table columns.
So, what I'm asking is, how do I get it to load my Family model properly with the name, etc. There are other columns in there (createdAt, updatedAt, etc) but I've just removed those for brevity.
Thanks in advance for any help. I've been stuck on this for 2 days now
Ok. So I feel like an idiot. Basically, I had a Strategy to use PascalNamingCase, which was looking for the column "Name" in the database, however, I put it as "name"...
So, the solution, ensure your column names match your naming strategy otherwise Adonis will pull out the columns but won't match them up as you thought it would.