【问题标题】:How can I query in Bookshelf/Knex on a BelongsToMany join table?如何在 BelongsToMany 连接表的 Bookshelf/Knex 中查询?
【发布时间】:2020-06-02 21:01:08
【问题描述】:

我在 Node 应用程序中通过 MySQL 运行 Bookshelf。

我有一个名为 Document 的模型和另一个名为 Tag 的模型,它们通过一个名为“map_tag_document”的表通过 belongsToMany 关系连接起来。

文档:

'use strict';

const bookshelf = require('../bootstrap/bookshelf_instance').bookshelf;
const Tag = require('./tag').model;

const Document = bookshelf.Model.extend({
        tableName: 'document',
        tags() {
            return this.belongsToMany(Tag, 'map_tag_document', 'document_id', 'tag_id')
        }
    },
    {
        jsonColumns: ['data']
    }
);

module.exports.model = Document;

标签:

'use strict';

const bookshelf = require('../bootstrap/bookshelf_instance').bookshelf;

const Tag = bookshelf.Model.extend({
    tableName: 'tag'
});

module.exports.model = Tag;

标签有一个“名称”列。

如何根据与文档关联的标签名称中出现的搜索字符串查询文档?

目前,我正在这样查询:

await new Document()
                .query((qb) => {
                    if (searchString)
                        qb.whereRaw(`(data->'$.description' LIKE "%${searchString}%" OR name LIKE "%${searchString}%")`)
                })
                .fetch({
                    withRelated: ['tags']
                });

查询连接表的正确语法是什么?

【问题讨论】:

    标签: mysql knex.js bookshelf.js


    【解决方案1】:

    想通了——可以对 Knex 查询构建器对象进行连接,如下所示:

            const documents = await new Document()
                .query((qb) => {
                    qb.join('map_tag_document', 'document.id', '=', 'map_tag_document.document_id')
                    qb.join('tag', 'tag.id', '=', 'map_tag_document.tag_id')
                    if (searchString)
                        qb.andWhereRaw(`(document.data->'$.description' LIKE "%${searchString}%" OR document.name LIKE "%${searchString}%" OR tag.name LIKE "%${searchString}%")`)
                })
                .fetch({
                    withRelated: ['tags']
                });
    

    【讨论】:

      猜你喜欢
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 2016-02-27
      • 2020-03-15
      • 1970-01-01
      相关资源
      最近更新 更多