@@ -232,26 +232,30 @@ export function getManyToManyRelation(schema: SchemaDef, model: string, field: s
232232 if ( ! fieldDef . array || ! fieldDef . relation ?. opposite ) {
233233 return undefined ;
234234 }
235+
236+ // in case the m2m relation field is inherited from a delegate base, get the base model
237+ const realModel = fieldDef . originModel ?? model ;
238+
235239 const oppositeFieldDef = requireField ( schema , fieldDef . type , fieldDef . relation . opposite ) ;
236240 if ( oppositeFieldDef . array ) {
237241 // Prisma's convention for many-to-many relation:
238242 // - model are sorted alphabetically by name
239243 // - join table is named _<model1>To<model2>, unless an explicit name is provided by `@relation`
240244 // - foreign keys are named A and B (based on the order of the model)
241- const sortedModelNames = [ model , fieldDef . type ] . sort ( ) ;
245+ const sortedModelNames = [ realModel , fieldDef . type ] . sort ( ) ;
242246
243247 let orderedFK : [ string , string ] ;
244- if ( model !== fieldDef . type ) {
248+ if ( realModel !== fieldDef . type ) {
245249 // not a self-relation, model name's sort order determines fk order
246- orderedFK = sortedModelNames [ 0 ] === model ? [ 'A' , 'B' ] : [ 'B' , 'A' ] ;
250+ orderedFK = sortedModelNames [ 0 ] === realModel ? [ 'A' , 'B' ] : [ 'B' , 'A' ] ;
247251 } else {
248252 // for self-relations, since model names are identical, relation field name's
249253 // sort order determines fk order
250254 const sortedFieldNames = [ field , oppositeFieldDef . name ] . sort ( ) ;
251255 orderedFK = sortedFieldNames [ 0 ] === field ? [ 'A' , 'B' ] : [ 'B' , 'A' ] ;
252256 }
253257
254- const modelIdFields = requireIdFields ( schema , model ) ;
258+ const modelIdFields = requireIdFields ( schema , realModel ) ;
255259 invariant ( modelIdFields . length === 1 , 'Only single-field ID is supported for many-to-many relation' ) ;
256260 const otherIdFields = requireIdFields ( schema , fieldDef . type ) ;
257261 invariant ( otherIdFields . length === 1 , 'Only single-field ID is supported for many-to-many relation' ) ;
0 commit comments