简体   繁体   中英

Bookshelf(knex) - belongsToMany relation not working

I have been trying to setup a relation between Posts and Tags using belongsToMany relation (Bookshelf). Here is my code:

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 route is:

.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()})
            })
    })

I have already added a table 'posts_tags' in database and all the database is seeded including this pivot table. So when I query in route, the relationship query does not even initiate. knex debug: sql: 'select posts .* from posts where id = ? limit ?'

Tables

posts - id title text created_at updated_at


tags - id name created_at updated_at


posts_tags - id post_id tag_id created_at updated_at


Is there any mistake(s) in code?

Sorry for this Post - I had just the typo:

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

widthRelated = withRelated!!!!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM