续集关联 N:M

我不知道为什么与 Sequelize 的关联对我不起作用。我尝试了几个函数,但我无法输入 N:M 的语法。我尝试了几种方法,但没有一种对我有用。如果有人可以帮助我,谢谢。这些是我的表格和我的陈述。


用户.js


'use strict'


const sequelize = require('sequelize')

const db = require('../database/database')


const modelUser = db.define('usuarios', {

    idusuario: {

        primaryKey: true,

        type: sequelize.INTEGER

    },

    username: {

        type: sequelize.STRING

    },

    password: {

        type: sequelize.STRING

    },

    email: {

        type: sequelize.STRING

    },

    victorias: {

        type: sequelize.INTEGER

    },

    muertes: {

        type: sequelize.INTEGER

    },

    admin: {

        type: sequelize.INTEGER

    }

}, {

    timestamps: false

})


module.exports = modelUser

标题.js


'use strict'


const sequelize = require('sequelize')

const db = require('../database/database')


const modelTitle = db.define('titulos', {

    idtitulo: {

        primaryKey: true,

        type: sequelize.INTEGER

    },

    titulo: {

        type: sequelize.STRING

    }

}, {

    timestamps: false

})


module.exports = modelTitle

titles_users.js


'use strict'


const sequelize = require('sequelize')

const db = require('../database/database')


const modelTitle = db.define('titulos', {

    fx_idtitulo: {

        type: sequelize.INTEGER

    },

    fx_idusuario: {

        type: sequelize.INTEGER

    }

}, {

    timestamps: false

})


module.exports = modelTitle

控制器.js


const TitlesUsers = require('../models/titles_users')

const Users = require('../models/user')

const Titles = require('../models/title')

    TitlesUsers.belongsTo(Users, {foreignKey: 'fx_idusuario', sourceKey: 'idusuario'});

    TitlesUsers.belongsTo(Titles, {foreignKey: 'fx_idtitulo', sourceKey: 'idtitulo'});


const users = await Users.findOne({ 

        include: [{model:Titles}],

        where: {idusuario:req.user}

    })


凤凰求蛊
浏览 197回答 1
1回答

沧海一幻觉

您需要使用belongsToMany以下方法指定关系:Users.belongsToMany(Titles, {through: TitlesUsers, foreignKey: 'fx_idusuario'});Titles.belongsToMany(Users, {through: TitlesUsers, foreignKey: 'fx_idtitulo'});请参阅Sequelize 文档中的示例。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript