Query.with() doesn't fill related models except for the first


#1

Hey all,

I’m currently working on a project and something has been not working for me as expected.

Assume the following Model:

class ShippingOrder extends Model {
    customer () {
        return this.belongsTo('App/Models/Customer', 'id', 'id');
    }
}

and in the controller I retrieve the ShippingOrder with

 const result =  await ShippingOrder
            .query()
            .with('customer')
            .fetch();

My first result in the array actually gives me the related model. The second one doesn’t

[  
   {  
      "id":1,
      "customerId":1,
      "created_at":"2018-04-08 19:27:36",
      "updated_at":"2018-04-08 19:27:36",
      "customer":{  
         "id":1,
         "name":"Patrick Dronk",
         "created_at":"2018-04-08 19:22:17",
         "updated_at":"2018-04-08 19:22:17"
      }
   },
   {  
      "id":2,
      "customerId":1,
      "created_at":"2018-04-08 19:27:36",
      "updated_at":"2018-04-08 19:27:36",
      "customer":null
   }
]

Am I querying it wrong or, does someone know what I’m doing wrong?


#2

hello, show your scheme.


#3
'use strict'

const Schema = use('Schema')

class ShippingOrderSchema extends Schema {
    up() {
        this.create('shipping_orders', (table) => {
            table.increments();
            table.integer('customerId').unsigned().references('id').inTable('customers').notNullable();
            table.timestamps();
        })
    }

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

module.exports = ShippingOrderSchema

#4

Try it like this

class ShippingOrder extends Model {
    customer () {
        return this.belongsTo('App/Models/Customer', 'customerId', 'id');
    }
}

Syntax:
belongsTo(relatedModel, primaryKey, foreignKey)

relatedModel - App/Models/Customer
primaryKey - customerId
foreignKey - id

https://adonisjs.com/docs/4.1/relationships#_belongs_to


#5

Thanks, that was the problem,
Not sure why I thought it was id.
Thanks!