adonisjs / lucid

AdonisJS SQL ORM. Supports PostgreSQL, MySQL, MSSQL, Redshift, SQLite and many more
https://lucid.adonisjs.com/
MIT License
1.07k stars 193 forks source link

Error .with(...).findOrFail is not a function #30

Closed ntvsx193 closed 8 years ago

ntvsx193 commented 8 years ago

let server = yield Server.with('machine').findOrFail(id) genarate 500 error .with(...).findOrFail is not a function

However, if i use some code as yield Server.with('machine').fetch() - response is ok.

App/Http/Controllers/ServerController:

'use strict'

const Server = use('App/Model/Server')

class ServersController {

  * index (request, response) {
    let servers = yield Server.with('machine').fetch()
    response.json(servers)
  }

  * show (request, response) {
    const id = request.param('id')
    let server = yield Server.with('machine').findOrFail(id)
    response.json(server)
  }

}

module.exports = ServersController

App/Model/Server:

'use strict'

const Lucid = use('Lucid')

class Server extends Lucid {

  machine () {
    return this.belongsTo('App/Model/Machine')
  }

}

module.exports = Server

App/Model/Machine

'use strict'

const Lucid = use('Lucid')

class Machine extends Lucid {

  servers () {
    return this.hasMany('App/Model/Server')
  }

}

module.exports = Machine
thetutlage commented 8 years ago

with is to eagerLoad relationships and findOrFail only work when intentionally fetching model instances. Here since you are going to load only 1 record, I would suggest to go this way.

let server = yield Server.findOrFail(id) // if error it fails early, instead of loading machine

// this line will load the related machine and it will add the result to the fetched instance
yield server.related('machine').load()

response.json(server)
ntvsx193 commented 8 years ago

Oh, yes, thank you! It'll be write in docs.