@@ -640,17 +640,49 @@ export class PrismaSchemaGenerator {
640640 ( attr ) => ( attr as PrismaFieldAttribute ) . name !== '@relation'
641641 ) ;
642642
643+ const relKeyPairs = getRelationKeyPairs ( f ) ;
644+
643645 if (
644646 // array relation doesn't need FK
645647 f . type . array ||
648+ // FK field is defined on this side
649+ relKeyPairs . length > 0 ||
646650 // opposite relation already has FK, we don't need to generate on this side
647651 ( oppositeRelationAttr && getAttributeArg ( oppositeRelationAttr , 'fields' ) )
648652 ) {
649- prismaField . attributes . push (
650- new PrismaFieldAttribute ( '@relation' , [
651- new PrismaAttributeArg ( undefined , new AttributeArgValue ( 'String' , relName ) ) ,
652- ] )
653- ) ;
653+ const relationArgs = [ new PrismaAttributeArg ( undefined , new AttributeArgValue ( 'String' , relName ) ) ] ;
654+ const isSelfRelation = f . type . reference . ref === ( f . $inheritedFrom ?? f . $container ) ;
655+ if ( relKeyPairs . length > 0 && ! isSelfRelation ) {
656+ // carry over "fields" and "references" args if not a self-relation
657+ relationArgs . push (
658+ new PrismaAttributeArg (
659+ 'fields' ,
660+ new AttributeArgValue (
661+ 'Array' ,
662+ relKeyPairs . map (
663+ ( pair ) =>
664+ new AttributeArgValue (
665+ 'FieldReference' ,
666+ new PrismaFieldReference ( pair . foreignKey . name )
667+ )
668+ )
669+ )
670+ )
671+ ) ;
672+ relationArgs . push (
673+ new PrismaAttributeArg (
674+ 'references' ,
675+ new AttributeArgValue (
676+ 'Array' ,
677+ relKeyPairs . map (
678+ ( pair ) =>
679+ new AttributeArgValue ( 'FieldReference' , new PrismaFieldReference ( pair . id . name ) )
680+ )
681+ )
682+ )
683+ ) ;
684+ }
685+ prismaField . attributes . push ( new PrismaFieldAttribute ( '@relation' , relationArgs ) ) ;
654686 } else {
655687 // generate FK field
656688 const oppositeModelIds = getIdFields ( oppositeRelationField . $container as DataModel ) ;
0 commit comments