【问题标题】:How to implement JOIN in Sequelize如何在 Sequelize 中实现 JOIN
【发布时间】:2021-10-05 16:21:10
【问题描述】:

我有三个表,结构描述如下:

用户表包含字段:idnamedate_created

库表包含字段:idcapacitydate_createduser_id

user_id 是 User 表的外键,Library 的每个实例都必须属于一个用户。

最后一个表是 Books 表,其中包含以下字段:idstatusdate_createdlibrary_id

library_id 是图书馆表的外键,一本书的每个实例都必须属于一个图书馆。

我想要实现的是一种在数据库中查询属于用户且状态为例如:borrowed

的图书的所有实例的方法

【问题讨论】:

标签: postgresql sequelize.js


【解决方案1】:

要首先实现连接,您需要在 sequelize 模型之间建立关联。 所以,在你的情况下

models.Library.hasMany(models.Books, {
    foreignKey: 'library_id'
})

models.Books.belongsTo(models.Library, {
    foreignKey: 'library_id'
})

models.Library.belongsTo(models.User, {
    foreignKey: 'user_id'
})

models.User.hasMany(models.Library, {
    foreignKey: 'user_id'
})

这里,models 是一个续集实例。 您可以在此处找到有关续集关联的更多信息 http://docs.sequelizejs.com/manual/tutorial/associations.html

现在,要查找属于用户的所有图书实例

models.User.findAll({
    include: [{
        model: models.Library,
        required: true, // do an INNER Join 
        include: [{
            model: models.Books,
            required: true,
            where: {
                status: 'borrowed'
            }
        }] t
    }],
    where: {
       user_id: 'some_user_id'
    }
})

【讨论】:

    【解决方案2】:

    我认为include 是您需要的,请查看以下查询:

    Books.findAll({
        include : { //<------ By this you can use association
            model : User ,
            where : { id : YOUR_USER_ID }
        },
        where : { status : 'borrowed' }    
    }).then(books => {
        if(books.length > 0) {
            console.log(books);
        } else {
            console.log("No books found");
        }
    })
    

    【讨论】:

    • 您需要先设置关联
    • 哦,好吧,对不起:)
    猜你喜欢
    • 1970-01-01
    • 2017-01-21
    • 2015-02-18
    • 1970-01-01
    • 2016-12-02
    • 2017-06-10
    • 1970-01-01
    • 2022-07-08
    相关资源
    最近更新 更多