Problem with Relationships

I’m trying to get “status” from one Model to another, like this:

Works.js

'use strict'

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

class Work extends Model {
  statuses () {
    this.hasOne('App/Models/WorkStatus')
  }

  customer () {
    this.hasOne('App/Models/User', 'id', 'customer_id')
  }
}

module.exports = Work

WorkStatus.js

'use strict'

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

class WorkStatus extends Model {
}

module.exports = WorkStatus

works_schema.js

'use strict'

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

class WorkSchema extends Schema {
  up () {
    this.create('works', (table) => {
      table.increments()
      table.string('name', 80).notNullable()
      table
        .integer('customer_id')
        .unsigned()
        .references('id')
        .inTable('users')
        .notNullable()
      table.string('address', 120).notNullable()
      table.string('neighbourhood', 80).notNullable()
      table.integer('number').notNullable()
      table.integer('cep', 8).notNullable()
      table
        .integer('status')
        .unsigned()
        .references('id')
        .inTable('work_statuses')
        .notNullable()
      table.timestamps()
    })
  }

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

module.exports = WorkSchema

work_status_schema.js

'use strict'

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

class WorkStatusSchema extends Schema {
  up () {
    this.create('work_statuses', (table) => {
      table.increments()
      table.string('name', 120).notNullable()
      table.timestamps()
    })
  }

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

module.exports = WorkStatusSchema

Then, in my code, i call it:

WorkController.js

const works = await Work.query().with('statuses').fetch()

return works

But when i access the route from postman, i receive this error:

Cannot destructure propertyrelatedQueryof 'undefined' or 'null'.

How i should proceed?

1 Like

You can return the relationship definition from the statuses method. https://adonisjs.com/docs/4.1/relationships#_defining_relation

  statuses () {
    return this.hasOne('App/Models/WorkStatus')
  }
2 Likes

hmm, I have similar problem