Can't get data with belongsTo relation

Hi!

I can’t figure out how to load data with belongsTo relation… Most likely some stupid mistake.

// User.js
citizenship () {
  return this.belongsTo('App/Models/Citizenship')
}
cars () {
  return this.belongsToMany('App/Models/Car')
}
// UserController.js
const User = use('App/Models/User')
const Citizenship = use('App/Models/Citizenship')
...
// Maybe there is way to make `where('id', id)` nicer?
const user = await User.query().where('id', id).with('citizenship').with('cars').first()
// user.$relations.car === {data}
// user.$relations.citizenship === null

// But user.$attributes.citizenship === 87 and 
let citizenship = await Citizenship.find(user.$attributes.citizenship)
// citizenship === {data}

Also tried with loadMany(), but result was still same :slightly_frowning_face:

It confuses me why is user.$relations.citizenship null while user.$attributes.citizenship is existing ID in citizenships table. :thinking:

belongsToMany works like charm tho

Can you turn on database logging and share the queries generated by this code

Hi @virk

I wonder why I never thought about logging queries…

But it got me even more confused
Logged query for:

User.query().where('id', id).with('citizenship').first()
{
  method: 'first',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ 673, 1 ],
  __knexQueryUid: 'c3a729e1-9ee5-4556-a384-1eb0c79053cb',
  sql: 'select * from "users" where "id" = ? limit ?'
}

But when I add cars back:

User.query().where('id', id).with('citizenship').with('cars').first()
{
  method: 'first',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ 673, 1 ],
  __knexQueryUid: '3f627d31-5415-46a6-b9c1-cee85fd9a354',
  sql: 'select * from `users` where `id` = ? limit ?'
}
{
  method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ 673 ],
  __knexQueryUid: 'eea926bf-8dd8-44b2-a08d-78fdd19cfd91',
  sql: 'select `cars`.*, `car_user`.`car_id` as `pivot_car_id`, ' +
    '`car_user`.`user_id` as `pivot_user_id` from `cars` inner join ' +
    '`car_user` on `cars`.`id` = `car_user`.`car_id` where ' +
    '`car_user`.`user_id` in (?)'
}

It feels like there is typo somewhere and it is skipping this query all together because of it.

Does the user table has citizenship_id?

Aaarrrggghhhh!!

Thx @virk! I own you one beer / coffee :smiley:

It has citizenship not citizenship_id:expressionless:
Thought it must be something small that I can’t find

Looked over so many times but kept missing same thing over and over…

Yeah, I believe the Lucid should complain for same. Something I’ll handle in v5

1 Like