我如何在BelongsToMany连接表上查询BookshelfKnex?

问题描述 投票:0回答:1

我在 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;

Tag:

'use strict';

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

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

module.exports.model = Tag;

标签有一个 "name "列。

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

目前,我的查询方式是这样的。

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个回答
0
投票

解决了--可以在Knex querybuilder对象上做连接,像这样。

        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']
            });
© www.soinside.com 2019 - 2024. All rights reserved.