0

Bem, eu criei uma relação many to many, assim como vi na documentação, alguns posts e alguns vídeos na internet, não consegui sucesso em nenhuma tentativa por algum erro meu que não consigo identificar.

O model:

Models/User.js

'use strict'

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

/** @type {import('@adonisjs/framework/src/Hash')} */
const Hash = use('Hash')

class User extends Model {
  static boot () {
    super.boot()

    /**
     * A hook to hash the user password before saving
     * it to the database.
     */
    this.addHook('beforeSave', async (userInstance) => {
      if (userInstance.dirty.password) {
        userInstance.password = await Hash.make(userInstance.password)
      }
    })

  }

  /**
   * A relationship on tokens is required for auth to
   * work. Since features like `refreshTokens` or
   * `rememberToken` will be saved inside the
   * tokens table.
   *
   * @method tokens
   *
   * @return {Object}
   */
  tokens () {
    return this.hasMany('App/Models/Token')
  }

  questions(){
    return this.belongsToMany('App/Models/Question','question_id','user_id','id','id')
  }

  static get traits () {
    return [
      '@provider:Adonis/Acl/HasRole',
      '@provider:Adonis/Acl/HasPermission'
    ]
  }

}

module.exports = User

Models/Question.js

'use strict'

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

class Question extends Model {

    alternatives(){
        return this.hasOne('App/Models/Alternative','id','question_id')
    }

    users(){
        return this.belongsToMany('App/Models/Users','user_id','question_id','id','id')
    }
}

module.exports = Question

O controller:

Controllers/Http/UserController.js

const User = use("App/Models/User")
const Question = use("App/Models/Question")

async storeQuestion({ request, response}) {

  const {question, alternatives, user_id} = request.post()
  const questionData = await Question.create(question)

  if(alternatives){
    await questionData.alternatives().create(alternatives)
    await questionData.load('alternatives')
  }

  const user = User.find(user_id)
  await user.questions().attach(questionData)
  await user.load('questions')

  return user
}

A migration da tabela pivot:

this.create('user_creates_question', (table) => {
  table.increments()
  table.integer('user_id').unsigned().references('users.id').onDelete('cascade').index('user_id')
  table.integer('question_id').unsigned().references('questions.id').onDelete('cascade').index('question_id')
  table.timestamps()
})

Quando eu executo a rota que chama este controller, é devolvido a seguinte mensagem:

user.questions is not a function

Embora seja criado a entidade Question e Alternative, não é terminada a função de attach().

6
  • você usou esse tutorial: adonisjs.com/docs/4.0/relationships#_belongs_to_many ?
    – novic
    29/10/2019 às 0:03
  • Sim, já tentei. Não to entendendo o porquê de questions() não ser uma "função" :( 29/10/2019 às 0:07
  • Você testou essa linha const user = User.find(user_id) pra ver se realmente retornar um user?
    – novic
    29/10/2019 às 0:08
  • Sim, todos os comandos funcionam até chegar await user.questions().attach(questionData) 29/10/2019 às 0:08
  • 1
    Feito, eu tentei evitar colocar tudo pra não ficar muita coisa, mas ai está. 29/10/2019 às 0:16

1 Resposta 1

1

Tive um problema semelhante recentemente resolvi usando o fetch ao invés do load, segue sugestão.

//Seu código
await user.load('questions')

//Sugestão de alteração
user.questionData = await user.questions().fetch()

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .