Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(db-postgres): joins to self collection #10182

Merged
merged 4 commits into from
Dec 26, 2024
Merged

fix(db-postgres): joins to self collection #10182

merged 4 commits into from
Dec 26, 2024

Conversation

r1tsuu
Copy link
Member

@r1tsuu r1tsuu commented Dec 26, 2024

What?

With Postgres, before join to self like:

import type { CollectionConfig } from 'payload'

export const SelfJoins: CollectionConfig = {
  slug: 'self-joins',
  fields: [
    {
      name: 'rel',
      type: 'relationship',
      relationTo: 'self-joins',
    },
    {
      name: 'joins',
      type: 'join',
      on: 'rel',
      collection: 'self-joins',
    },
  ],
}

wasn't possible, even though it's a valid usage.

How?

Now, to differentiate parent self_joins and children self_joins we do additional alias for the nested select - "4d3cf2b6_1adf_46a8_b6d2_3e1c3809d737":

select 
  "id", 
  "rel_id", 
  "updated_at", 
  "created_at", 
  (
    select 
      coalesce(
        json_agg(
          json_build_object('id', "joins_alias".id)
        ), 
        '[]' :: json
      ) 
    from 
      (
        select 
          "created_at", 
          "rel_id", 
          "id" 
        from 
          "self_joins" "4d3cf2b6_1adf_46a8_b6d2_3e1c3809d737" 
        where 
          "4d3cf2b6_1adf_46a8_b6d2_3e1c3809d737"."rel_id" = "self_joins"."id" 
        order by 
          "4d3cf2b6_1adf_46a8_b6d2_3e1c3809d737"."created_at" desc 
        limit 
          $1
      ) "joins_alias"
  ) as "joins_alias" 
from 
  "self_joins" 
where 
  "self_joins"."id" = $2 
order by 
  "self_joins"."created_at" desc 
limit 
  $3

Fixes #10144

-->

@r1tsuu r1tsuu merged commit a0d8131 into main Dec 26, 2024
66 checks passed
@r1tsuu r1tsuu deleted the self-join branch December 26, 2024 18:47
Copy link
Contributor

🚀 This is included in version v3.12.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Postgres: Self-Join Not Working
1 participant