Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

316
Visualizações
Bookshelf.js relation with foreign key from a property in json

I have 2 models

  • Book: id, name, data (json)
  • Author: id, name

I want to extend Book model with method author which return the author when query withRelated. This could be easy to achieve with below snippet, provided that I have author_id in Book

const Book = bookshelf.model('Book', {
  tableName: 'books',
  author() {
    return this.belongsTo('Author', 'author_id', 'id')
  }
})

But the problem is, author_id is a property of data (which is json type). I tried the snippet below but it not worked

const Book = bookshelf.model('Book', {
  tableName: 'books',
  author() {
    return this.belongsTo('Author', `data->>'author_id'`, 'id')
  }
})

If I am not allowed to have any changes in the origin models, how could I get author in this case? Thanks in advance.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Came up with a solution that worked, a little bit tricky combination of related and event hook

const Book = bookshelf.model('Book', {
  tableName: 'books',
  initialize: function() {
    this.on('fetched', async function(model) {
      model.set('author_id', (model.get('data') || {}).author_id || null)
      const author = await model.related('author').fetch()
      model.set('author', author)
    })
  },
  author() {
    return this.belongsTo('Author')
  }
})
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda