Help needed with a query


#1

I’m having some trouble building a query on my first Adonis project. I’ve included some related excerpts below.
Specifically I’m attempting to write a query for index() in ZoneController.js. I would like to return a list of all zones within the group in the response for this method, only if the group is associated with the requesting/authenticated user.

The error received is TypeError: user.group(...).zone is not a function, and after looking at it I’m aware of why the TypeError is being thrown, but having trouble finding a way to accomplish what I want.

App/Models/User.js

'use strict'

class User extends Model {
  ...
  group () {
    return this.belongsToMany('App/Models/Group')
  }
}

App/Models/Group.js

'use strict'

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

class Group extends Model {
  user () {
    return this.belongsToMany('App/Models/User')
  }

  zone () {
    return this.hasMany('App/Models/Zone')
  }
}
...

App/Models/Zone.js

'use strict'

const Model = use('Model')

class Zone extends Model {
  group () {
    return this.belongsTo('App/Models/Group')
  }
}

App/Controllers/Http/ZoneController.js

'use strict'

const User = use('App/Models/User')
const Zone = use('App/Models/Zone')
const Group = use('App/Models/Group')

/**
 * Resourceful controller for interacting with zones
 */
class ZoneController {
  /**
   * Show a list of all zones.
   * GET zones
   *
   * @param {object} ctx
   * @param {Response} ctx.response
   */
  async index ({ auth, params, response}) {
    const user = await auth.getUser()
    const { group_id } = params
    const zones = await user.group().zone().where('groups.id', group_id).fetch()

    response.status(201).json({
      message: 'Success! The groups zones were retrieved',
      zones: zones
    })
  }
}

#2

Is there a better, more eloquent way of accomplishing this than replacing:

const zones = await user.group().zone().where('groups.id', group_id).fetch()

with

const group = await user.group().where('groups.id', group_id).first()
const zones = await group.zone().fetch()

#3

please try if this work

const zones = await Group
                 .query()
                 .where('id', group_id)
                 .with('zone')
                 .fetch()

ref: https://adonisjs.com/docs/4.0/relationships#_adding_runtime_constraints

hope its help :grinning: