diff --git a/packages/core/database/src/fields/belongs-to-many-field.ts b/packages/core/database/src/fields/belongs-to-many-field.ts index b0fc12ac2..df3a1dd13 100644 --- a/packages/core/database/src/fields/belongs-to-many-field.ts +++ b/packages/core/database/src/fields/belongs-to-many-field.ts @@ -55,9 +55,15 @@ export class BelongsToManyField extends RelationField { if (database.hasCollection(through)) { Through = database.getCollection(through); } else { - Through = database.collection({ + const throughCollectionOptions = { name: through, - }); + }; + + if (this.collection.collectionSchema()) { + throughCollectionOptions['schema'] = this.collection.collectionSchema(); + } + + Through = database.collection(throughCollectionOptions); Object.defineProperty(Through.model, 'isThrough', { value: true }); } diff --git a/packages/plugins/collection-manager/src/__tests__/fields/belongsToMany.test.ts b/packages/plugins/collection-manager/src/__tests__/fields/belongs-to-many.test.ts similarity index 54% rename from packages/plugins/collection-manager/src/__tests__/fields/belongsToMany.test.ts rename to packages/plugins/collection-manager/src/__tests__/fields/belongs-to-many.test.ts index 5ded8d5af..bbfda25df 100644 --- a/packages/plugins/collection-manager/src/__tests__/fields/belongsToMany.test.ts +++ b/packages/plugins/collection-manager/src/__tests__/fields/belongs-to-many.test.ts @@ -51,5 +51,29 @@ describe('belongsToMany', () => { }); expect(throughCollection.get('sortable')).toEqual(false); + const collectionManagerSchema = process.env.COLLECTION_MANAGER_SCHEMA; + const mainSchema = process.env.DB_SCHEMA || 'public'; + + if (collectionManagerSchema && mainSchema != collectionManagerSchema && db.inDialect('postgres')) { + expect(throughCollection.get('schema')).toEqual(collectionManagerSchema); + + const tableName = db.getCollection('post_tags').model.tableName; + + const mainSchema = process.env.DB_SCHEMA || 'public'; + + const tableExists = async (tableName: string, schema: string) => { + const sql = `SELECT EXISTS(SELECT 1 FROM information_schema.tables + WHERE table_schema = '${schema}' + AND table_name = '${tableName}')`; + + const results = await db.sequelize.query(sql, { type: 'SELECT' }); + + const exists = results[0]['exists']; + return exists; + }; + + expect(await tableExists(tableName, collectionManagerSchema)).toBe(true); + expect(await tableExists(tableName, mainSchema)).toBe(false); + } }); }); diff --git a/packages/plugins/collection-manager/src/__tests__/http-api/belongsToMany.test.ts b/packages/plugins/collection-manager/src/__tests__/http-api/belongs-to-many.test.ts similarity index 100% rename from packages/plugins/collection-manager/src/__tests__/http-api/belongsToMany.test.ts rename to packages/plugins/collection-manager/src/__tests__/http-api/belongs-to-many.test.ts