hasMany on multiple columns

Hi,

I was wondering if it was possible to have a has many relationship on multiple columns in the same table.

Here’s the scenario:

Tables:

  • proposals [id, version, text]
  • proposals_changelog [id, proposal_id, version, text]

Model:

'use strict';

/** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */
const Model = use('Model');

class Proposal extends Model {
  changelog() {
    return this.hasMany('App/Models/ProposalChangelog', 'id', 'proposal_id');
  }
}

module.exports = Proposal;

However, I need hasMany to be based on two fields, for example:

this.hasMany('App/Models/ProposalChangelog', ['id', 'version'], ['proposal_id','version']);

It is possible?
How to make the relationship with two fields?

Thank you!

It is not possible. The API does not support that.

  /**
   * Returns an instance of @ref('HasMany') relation
   *
   * @method hasMany
   *
   * @param  {String|Class}  relatedModel
   * @param  {String}        primaryKey
   * @param  {String}        foreignKey
   *
   * @return {HasMany}
   */
  hasMany (relatedModel, primaryKey, foreignKey) {
    relatedModel = typeof (relatedModel) === 'string' ? ioc.use(relatedModel) : relatedModel

    primaryKey = primaryKey || this.constructor.primaryKey
    foreignKey = foreignKey || this.constructor.foreignKey

    return new HasMany(this, relatedModel, primaryKey, foreignKey)
  }

primaryKey and foreignKey are strings not arrays.

1 Like