UNPKG

@adonisjs/lucid

Version:

SQL ORM built on top of Active Record pattern

63 lines (62 loc) 2.11 kB
/* * @adonisjs/lucid * * (c) Harminder Virk <virk@adonisjs.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseRelation } from './base.js'; /** * Many to many factory relation */ export class ManyToMany extends BaseRelation { relation; attributesForPivotTable = {}; constructor(relation, factory) { super(factory); this.relation = relation; this.relation.boot(); } /** * Make relationship and set it on the parent model instance */ async make(parent, callback, count) { const builder = this.compile(this, parent, callback); const instances = await builder.makeStubbedMany(count || 1); parent.$pushRelated(this.relation.relationName, instances); } /** * Define pivot attributes */ pivotAttributes(attributes) { this.attributesForPivotTable = attributes; return this; } /** * Persist relationship and set it on the parent model instance */ async create(parent, callback, count) { const builder = this.compile(this, parent, callback); const instances = await builder.createMany(count || 1); /** * Create object for the pivot table. We merge user defined pivot attributes with * the required foreign keys */ const relatedForeignKeyValues = instances.reduce((result, one, index) => { const [, relatedForeignKeyValue] = this.relation.getPivotRelatedPair(one); result[relatedForeignKeyValue] = Array.isArray(this.attributesForPivotTable) ? this.attributesForPivotTable[index] || {} : this.attributesForPivotTable || {}; return result; }, {}); /** * Make pivot insert query */ await this.relation.client(parent, this.ctx?.$trx).attach(relatedForeignKeyValues); /** * Setup in-memory relationship */ parent.$pushRelated(this.relation.relationName, instances); } }