I have a polymorphic many to many relation. The polymorphic join table has a $beforeInsert hook:
class Membership extends Model {
static tableName = 'memberships';
async $beforeInsert(ctx) {
await super.$beforeInsert(ctx);
const now = moment().utc().format();
this.createdAt = now;
this.updatedAt = now;
}
}
class User extends Model {
static tableName = 'users';
static className = 'User';
static get relationMappings() {
const Organization = require('./Organization').default; // eslint-disable-line global-require
const Membership = require('./Membership').default; // eslint-disable-line global-require
return {
organizations: {
relation: BaseModel.ManyToManyRelation,
modelClass: Organization,
filter: {
memberType: User.className,
objectType: Organization.className,
},
join: {
from: `${User.tableName}.id`,
to: `${Organization.tableName}.id`,
through: {
from: `${Membership.tableName}.memberId`,
to: `${Membership.tableName}.objectId`,
beforeInsert(model) {
model.memberType = User.className;
model.objectType = Organization.className;
},
},
},
},
};
}
}
When I'm trying create a new organization for the user it fails because the Membership's $beforeInsert wasn't called:
user.$relatedQuery('organizations').insert({ name: 'My Org' })
insert into "memberships" ("memberId", "memberType", "objectId", "objectType") values (?, ?, ?, ?) returning "objectId" undefined
error: null value in column "createdAt" violates not-null constraint
You need to specify the join table model in the relationMapping:
through: {
modelClass: Membership,
from: `${Membership.tableName}.memberId`,
to: `${Membership.tableName}.objectId`,
beforeInsert(model) {
model.memberType = User.className;
model.objectType = Organization.className;
},
}
@koskimas ahh! thank you!
Most helpful comment
You need to specify the join table model in the
relationMapping: