Skip to content

Literal "order" of Custom Pivot Entity properties breaks the join query #3040

@wyemun

Description

@wyemun

Describe the bug
When using Custom Pivot Entity , the order of the two foreign keys matters.

To Reproduce
Steps to reproduce the behavior:

  1. Create the following entity schema:
export class Price {
  @PrimaryKey({type: 'uuid'})
  id: string = uuid.v4()
  
  @ManyToMany({ entity = () => Title, pivotEntity: () => SomePivot }, 'prices')
  titles = new Collection<Title>(this)
}

export class Title{
  @PrimaryKey({type: 'uuid'})
  id: string = uuid.v4()
  
  @ManyToMany({ entity = () => Title, pivotEntity: () => SomePivot }, 'titles')
  prices= new Collection<Price >(this)
}

export class SomePivot {
  @PrimaryKey({type: 'uuid'})
  id: string = uuid.v4()
  
  @ManyToOne({ entity = () => Title, fieldName: 'title_id' })
  title: Title
  
  @ManyToOne({ entity = () => Price , fieldName: 'price_id' })
  price: Price
}
  1. Then when you run the following query:
const data = await em.findOne(Price, {id: '<id here>'}, {populate: ['titles']})

it will then return empty array.

  1. However if you reverse the order of the properties in SomePivot:
export class SomePivot {
  @PrimaryKey({type: 'uuid'})
  id: string = uuid.v4()

 @ManyToOne({ entity = () => Price , fieldName: 'price_id' })
  price: Price
  
  @ManyToOne({ entity = () => Title, fieldName: 'title_id' })
  title: Title
}

The result will be retrieved correctly.

Expected behavior
Should return the related populated data correctly in custom pivot entity solution regardless of the order of the property

Additional context
Upon checking the debug log, you can see the query being done incorrectly:

select 
  "t0".*, "s1"."price_id" as "fk__price_id", "s1"."title_id" as "fk__title_id"
from
  "titles" as "t0"
left join "some_pivots" as "s1" on
  "t0"."id" = "s1"."title_id"
where
  "s1"."title_id" in ('<id here>') # <-- where this should be "s1"."price_id" instead

Versions

Dependency Version
node 16.14.2
typescript 4.6.3
mikro-orm 5.1.2
database postgres

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions