gpt4 book ai didi

javascript - Bookshelf.js与json属性中的外键的关系

转载 作者:行者123 更新时间:2023-12-01 16:16:51 26 4
gpt4 key购买 nike

我有2个型号

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

  • 我想用 Book方法扩展 author模型,该方法在查询 withRelated时返回作者。如果我在 author_id中有 Book,则可以使用下面的代码片段轻松实现
    const Book = bookshelf.model('Book', {
    tableName: 'books',
    author() {
    return this.belongsTo('Author', 'author_id', 'id')
    }
    })
    但是问题是, author_iddata(是json类型)的属性。我尝试了以下代码段,但没有用
    const Book = bookshelf.model('Book', {
    tableName: 'books',
    author() {
    return this.belongsTo('Author', `data->>'author_id'`, 'id')
    }
    })
    如果不允许我对原始模型进行任何更改,在这种情况下如何获得 author?提前致谢。

    最佳答案

    提出了一个可行的解决方案,将related和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')
    }
    })

    关于javascript - Bookshelf.js与json属性中的外键的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63189968/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com