lucid: Fail load relation on empty value fkey column

I catch error when load relation on empty fkey column

E_UNSAVED_MODEL_INSTANCE: Cannot process relation, since Sim model is not persisted to database or relational value is undefined
  • adonis-lucid version 4.0.15
  • database driver pg

Http controller action

async show ({ response, params }) {
  const sim = await Sim.findOrFail(params.id)
  await sim.load('company')
  response.json(sim)
}

Models

class Sim extends Model {
  static get table () {
    return 'sims'
  }

  company () {
    return this.belongsTo('App/Models/Company')
  }
}
class Company extends Model {
  static get table () {
    return 'companies'
  }
}

Database data

Table sims

id iccid company_id
1 123123123 null

Table companies

id name
100500 Pew pew

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 34 (33 by maintainers)

Most upvoted comments

Writing working code is your problem, it’s not the ORM problem to work with bad values.

Simply write a check

async show ({ response, params }) {
  const sim = await Sim.findOrFail(params.id)
  if (sim.company_id) {
   await sim.load('company')
  }
  response.json(sim)
}

Fixed already and released as 4.0.17

I got excited with the closure of the issue. I had a changes in the @adonisjs/lucid component and I was happy that everything worked. But it’s not so.

I send PR https://github.com/adonisjs/adonis-lucid/pull/171 with changes for load relations with same null values fkeys. All tests passed.

It’s big problem on check if fkey exist for big relations list as:

const sim = await Sim.query()
  .with('modem')
  .with('usage')
  .with('company')
  .with('stat')
  .with('changed_company')
  .with('changed_company.user')
  .with('changed_status')
  .with('changed_status.user')
  .where('id', params.id)
  .first()

if (!sim) {
  return response.notFound()
}

response.json(sim)