簡體   English   中英

Bookshelf(knex) - belongsToMany關系不起作用

[英]Bookshelf(knex) - belongsToMany relation not working

我一直在嘗試使用belongsToMany關系(Bookshelf)設置帖子和標簽之間的關系。 這是我的代碼:

db.js

const Post = bookshelf.Model.extend({
    tableName: 'posts',
    hasTimestamps: true,
    tags: function(){
        return this.belongsToMany(Tag)
    }
})

const Tag = bookshelf.Model.extend({
    tableName: 'tags',
    posts: function(){
        return this.belongsToMany(Post)
    }
})

// Pivot table
const PostTag = bookshelf.Model.extend({
    tableName: 'posts_tags',
    post: function(){
        return this.belongsTo(Post)
    },
    tag: function(){
        return this.belongsTo(Tag)
    }

})

獲取路線是:

.get('/:id', (req, res, next) => {
        db
            .Post
            .where('id', req.params.id)
            .fetch({widthRelated: ['tags'], require:true})
            .then((data)=> {
                return res.json({data, ralation: data.related('tags').toJSON()})
            })
    })

我已經在數據庫中添加了一個表'posts_tags',並且所有數據庫都包含了這個數據透視表。 因此,當我在路由中查詢時,關系查詢甚至不會啟動。 knex debug: sql:'select posts 。* from posts where id =? 限制?'

帖子 - id標題文本created_at updated_at


tags - id name created_at updated_at


posts_tags - id post_id tag_id created_at updated_at


代碼中有錯誤嗎?

對不起這篇文章 - 我只是錯字:

.fetch({widthRelated: ['tags'], require:true})

widthRelated = withRelated !!!!!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM