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: join field works on collections with versions enabled #8715

Open
wants to merge 6 commits into
base: beta
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions packages/db-mongodb/src/queryDrafts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,23 @@ import { combineQueries, flattenWhereToOperators } from 'payload'
import type { MongooseAdapter } from './index.js'

import { buildSortParam } from './queries/buildSortParam.js'
import { buildJoinAggregation } from './utilities/buildJoinAggregation.js'
import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js'
import { withSession } from './withSession.js'

export const queryDrafts: QueryDrafts = async function queryDrafts(
this: MongooseAdapter,
{ collection, limit, locale, page, pagination, req = {} as PayloadRequest, sort: sortArg, where },
{
collection,
joins,
limit,
locale,
page,
pagination,
req = {} as PayloadRequest,
sort: sortArg,
where,
},
) {
const VersionModel = this.versions[collection]
const collectionConfig = this.payload.collections[collection].config
Expand Down Expand Up @@ -89,7 +100,29 @@ export const queryDrafts: QueryDrafts = async function queryDrafts(
paginationOptions.options.limit = limit
}

const result = await VersionModel.paginate(versionQuery, paginationOptions)
let result

const aggregate = await buildJoinAggregation({
adapter: this,
collection,
collectionConfig,
joins,
limit,
locale,
query: versionQuery,
versions: true,
})

// build join aggregation
if (aggregate) {
result = await VersionModel.aggregatePaginate(
VersionModel.aggregate(aggregate),
paginationOptions,
)
} else {
result = await VersionModel.paginate(versionQuery, paginationOptions)
}

const docs = JSON.parse(JSON.stringify(result.docs))

return {
Expand Down
11 changes: 7 additions & 4 deletions packages/db-mongodb/src/utilities/buildJoinAggregation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ type BuildJoinAggregationArgs = {
locale: string
// the where clause for the top collection
query?: Where
/** whether the query is from drafts */
versions?: boolean
}

export const buildJoinAggregation = async ({
Expand All @@ -25,6 +27,7 @@ export const buildJoinAggregation = async ({
limit,
locale,
query,
versions,
}: BuildJoinAggregationArgs): Promise<PipelineStage[] | undefined> => {
if (Object.keys(collectionConfig.joins).length === 0 || joins === false) {
return
Expand Down Expand Up @@ -90,15 +93,15 @@ export const buildJoinAggregation = async ({

if (adapter.payload.config.localization && locale === 'all') {
adapter.payload.config.localization.localeCodes.forEach((code) => {
const as = `${join.schemaPath}${code}`
const as = `${versions ? `version.${join.schemaPath}` : join.schemaPath}${code}`

aggregate.push(
{
$lookup: {
as: `${as}.docs`,
foreignField: `${join.field.on}${code}`,
from: slug,
localField: '_id',
localField: versions ? 'parent' : '_id',
pipeline,
},
},
Expand Down Expand Up @@ -131,15 +134,15 @@ export const buildJoinAggregation = async ({
} else {
const localeSuffix =
join.field.localized && adapter.payload.config.localization && locale ? `.${locale}` : ''
const as = `${join.schemaPath}${localeSuffix}`
const as = `${versions ? `version.${join.schemaPath}` : join.schemaPath}${localeSuffix}`

aggregate.push(
{
$lookup: {
as: `${as}.docs`,
foreignField: `${join.field.on}${localeSuffix}`,
from: slug,
localField: '_id',
localField: versions ? 'parent' : '_id',
pipeline,
},
},
Expand Down
1 change: 0 additions & 1 deletion packages/db-sqlite/src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ export const init: Init = async function init(this: SQLiteAdapter) {
disableNotNull: !!collection?.versions?.drafts,
disableUnique: false,
fields: collection.fields,
joins: collection.joins,
locales,
tableName,
timestamps: collection.timestamps,
Expand Down
3 changes: 0 additions & 3 deletions packages/db-sqlite/src/schema/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ type Args = {
disableRelsTableUnique?: boolean
disableUnique: boolean
fields: Field[]
joins?: SanitizedJoins
locales?: [string, ...string[]]
rootRelationships?: Set<string>
rootRelationsToBuild?: RelationMap
Expand Down Expand Up @@ -95,7 +94,6 @@ export const buildTable = ({
disableRelsTableUnique,
disableUnique = false,
fields,
joins,
locales,
rootRelationships,
rootRelationsToBuild,
Expand Down Expand Up @@ -144,7 +142,6 @@ export const buildTable = ({
disableUnique,
fields,
indexes,
joins,
locales,
localesColumns,
localesIndexes,
Expand Down
30 changes: 0 additions & 30 deletions packages/db-sqlite/src/schema/traverseFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ type Args = {
fields: (Field | TabAsField)[]
forceLocalized?: boolean
indexes: Record<string, (cols: GenericColumns) => IndexBuilder>
joins?: SanitizedJoins
locales: [string, ...string[]]
localesColumns: Record<string, SQLiteColumnBuilder>
localesIndexes: Record<string, (cols: GenericColumns) => IndexBuilder>
Expand Down Expand Up @@ -84,7 +83,6 @@ export const traverseFields = ({
fields,
forceLocalized,
indexes,
joins,
locales,
localesColumns,
localesIndexes,
Expand Down Expand Up @@ -669,7 +667,6 @@ export const traverseFields = ({
fields: field.fields,
forceLocalized,
indexes,
joins,
locales,
localesColumns,
localesIndexes,
Expand Down Expand Up @@ -725,7 +722,6 @@ export const traverseFields = ({
fields: field.fields,
forceLocalized: field.localized,
indexes,
joins,
locales,
localesColumns,
localesIndexes,
Expand Down Expand Up @@ -782,7 +778,6 @@ export const traverseFields = ({
fields: field.tabs.map((tab) => ({ ...tab, type: 'tab' })),
forceLocalized,
indexes,
joins,
locales,
localesColumns,
localesIndexes,
Expand Down Expand Up @@ -839,7 +834,6 @@ export const traverseFields = ({
fields: field.fields,
forceLocalized,
indexes,
joins,
locales,
localesColumns,
localesIndexes,
Expand Down Expand Up @@ -937,30 +931,6 @@ export const traverseFields = ({

break

case 'join': {
// fieldName could be 'posts' or 'group_posts'
// using `on` as the key for the relation
const localized = adapter.payload.config.localization && field.localized
const fieldSchemaPath = `${fieldPrefix || ''}${field.name}`
let target: string
const joinConfig = joins[field.collection].find(
({ schemaPath }) => fieldSchemaPath === schemaPath,
)
if (joinConfig.targetField.hasMany) {
target = `${adapter.tableNameMap.get(toSnakeCase(field.collection))}${adapter.relationshipsSuffix}`
} else {
target = `${adapter.tableNameMap.get(toSnakeCase(field.collection))}${localized ? adapter.localesSuffix : ''}`
}
relationsToBuild.set(fieldName, {
type: 'many',
// joins are not localized on the parent table
localized: false,
relationName: field.on.replaceAll('.', '_'),
target,
})
break
}

default:
break
}
Expand Down
3 changes: 3 additions & 0 deletions packages/drizzle/src/find/buildFindManyArgs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type BuildFindQueryArgs = {
joins?: BuildQueryJoinAliases
locale?: string
tableName: string
versions?: boolean
}

export type Result = {
Expand All @@ -34,6 +35,7 @@ export const buildFindManyArgs = ({
joins = [],
locale,
tableName,
versions,
}: BuildFindQueryArgs): Record<string, unknown> => {
const result: Result = {
extras: {},
Expand Down Expand Up @@ -97,6 +99,7 @@ export const buildFindManyArgs = ({
tablePath: '',
topLevelArgs: result,
topLevelTableName: tableName,
versions,
})

return result
Expand Down
3 changes: 3 additions & 0 deletions packages/drizzle/src/find/findMany.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type Args = {
adapter: DrizzleAdapter
fields: Field[]
tableName: string
versions?: boolean
} & Omit<FindArgs, 'collection'>

export const findMany = async function find({
Expand All @@ -28,6 +29,7 @@ export const findMany = async function find({
skip,
sort,
tableName,
versions,
where: whereArg,
}: Args) {
const db = adapter.sessions[await req.transactionID]?.db || adapter.drizzle
Expand Down Expand Up @@ -71,6 +73,7 @@ export const findMany = async function find({
joinQuery,
joins,
tableName,
versions,
})

selectDistinctMethods.push({ args: [offset], method: 'offset' })
Expand Down
Loading