ormadonis.jslucid

Loading `belongsToMany` relation using the `with` method always returning an empty array


I have 2 models, Person and PersonType with a belongsToMany relation.

The problem is that when I try to get all the PersonTypes related to a Person using the query().with() method, it is always returning an empty array even if I have the right data in the 3 tables people, person_type and the intermdiate person_person_type.

This is the code that is trying to load the people with their types:

const Person = use('App/Models/Person')

const people = await Person.query().with('types')

This is what I got from the code above:

[
    {
      "id": 3,
      "firstName": "Eleandro",
      "lastName": "Duzentos",
      "types": []
    },
    {
      "id": 5,
      "firstName": "Lorem",
      "lastName": "Ipsum",
      "types": []
    }
]

This is what it should return:

[
    {
      "id": 3,
      "firstName": "Eleandro",
      "lastName": "Duzentos",
      "types": [
          {
              name: "Requester",
              slug: "requester"
          },
          {
              "name": "Provider",
              "slug": "provider"
          },
      ]
    },
    {
      "id": 5,
      "firstName": "Lorem",
      "lastName": "Ipsum",
      "types": [
           {
              "name": "Requester",
              "slug": "requester"
           }
        ]
    }
]

Bellow is each models and their database migrations:

Person:

'use strict'

const Model = use('Model')

class Person extends Model {
  static get table () {
    return 'people'
  }

  types() {
    return this.belongsToMany('App/Models/PersonType')
      .withTimestamps()
  }
}

module.exports = Person
'use strict'

/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use('Schema')

class CreatePeopleSchema extends Schema {
  up () {
    this.create('people', (table) => {
      table.increments()

      table.string('first_name')
      table.string('last_name')
      table.date('birth_date')
      table.string('address')
      table.string('identification_number').nullable()

      table.integer('naturality_id').unsigned().index()
      table
        .foreign('naturality_id')
        .references('id')
        .inTable('municipalities')
        .onDelete('cascade')

      table.integer('person_genre_id').unsigned().index()
      table
        .foreign('person_genre_id')
        .references('id')
        .inTable('person_genres')
        .onDelete('cascade')

      table.boolean('is_activated').default(false).notNullable()

      table.timestamps()

      table.timestamp('deleted_at').nullable()
    })
  }

  down () {
    this.drop('people')
  }
}

module.exports = CreatePeopleSchema

PersonType:

'use strict'

const Model = use('Model')

class PersonType extends Model {
  people() {
    return this.belongsToMany('App/Models/Person')
      .withTimestamps()
  }
}

module.exports = PersonType
'use strict'

/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use('Schema')

class CreatePersonTypesSchema extends Schema {
  up() {
    this.create('person_types', (table) => {
      table.increments()

      table.string('name').unique()
      table.string('slug').unique().index()
      table.text('description').nullable()
      table.string('icon').nullable()

      table.timestamps()
    })
  }

  down() {
    this.drop('person_types')
  }
}

module.exports = CreatePersonTypesSchema

and the intermediate table:

'use strict'

/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use('Schema')

class PersonPersonTypeSchema extends Schema {
  up () {
    this.create('person_person_type', (table) => {
      table.increments()

      table.integer('person_id').unsigned().index()
      table
        .foreign('person_id')
        .references('id')
        .inTable('people')
        .onDelete('cascade')

      table.integer('person_type_id').unsigned().index()
      table
        .foreign('person_type_id')
        .references('id')
        .inTable('person_types')
        .onDelete('cascade')

      table.timestamps()
    })
  }

  down () {
    this.drop('person_person_type')
  }
}

module.exports = PersonPersonTypeSchema

This is the query Ludic is performing:

select `person_types`.*, `person_person_type`.`person_type_id` as `pivot_person_type_id`, `person_person_type`.`person_id` as `pivot_person_id` from `person_types` inner join `person_person_type` on `person_types`.`id` = `person_person_type`.`person_type_id` where `person_person_type`.`person_id` in (?, ?)

What I'm doing wrong?


Solution

  • Using pivot table name in association method and handle response format using toJSON()

    'use strict'
    
    const Model = use('Model')
    
    class Person extends Model {
      static get table () {
        return 'people'
      }
    
      types() {
        return this.belongsToMany('App/Models/PersonType')
          .pivotTable('person_type')
      }
    }
    
    module.exports = Person