node.js - Sequelize : Use multiple keys from source to include target model

标签 node.js postgresql sequelize.js

我有一个类似的模型,它将喜欢的项目的 id、user.id、business.id 及其项目类型存储为字符串。

const Like = sequelize.define('like', {
businessId : {type: DataTypes.INTEGER, allowNull: false},
itemId: {type: DataTypes.INTEGER, allowNull: false},
userId: {type: DataTypes.INTEGER, allowNull: false},
type: {type: DataTypes.STRING}})

元素可以是轿车、卡车或货车。都有自己的模型。

我想查询用户的所有点赞,并将它们分离到查询中包含的受尊重的模型中

我有一个像这样的模型协会:

Like.associate = function(models) {
  Like.hasOne(models.sedan, {sourceKey: 'itemId', foreignKey: 'id'})};

这让我可以包含我的轿车模型,并通过“itemId”和“sedan.id”等连接它们。

问题是,在 postgres 数据库中,id 从 1 开始,然后递增,因此 sedan.id 和卡车.id 都可以有 id = 5,我将其存储在类似的 itemId 中,以及类型键中的项目类型。

例如:

businessId : 23,
itemId: 5, // This id belongs to the item which can come from 'sedan','truck','van'
userId: 12,
type: 'Sedan' // This section lets you know where the id came from

我最终想做的是获得所有用户的喜欢,并包括其他受到他们尊重的喜欢的模型。

我的查询看起来如何。

Like.findAll({
    where: {userId: userId},
    include: [
        {
            model: Sedan,
            required: false
        },
        {
            model: Truck,
            required: false
        },
        {
            model: Van,
            required: false
        }
    ]
})

这不起作用,因为卡车的 ID 也可以调用轿车的 ID。我无法将类型添加到“where”

where: {userId: userId, type: 'Sedan'}

因为它会影响其余包含的模型,而且我似乎找不到如何将类似类型作为过滤器添加到每个包含的模型中

我也尝试将其添加到类似模型的关联部分,但似乎找不到添加类型的方法。 希望有类似“sourceScope”的东西。 例如:

Like.hasOne(models.product, {sourceKey: 'itemId', foreignKey: 'id', sourceScope: {type: 'Sedan'})

但我似乎找不到一种方法来绑定(bind)项目类型。

有没有办法做到这一点或有更好的方法来完成整个事情? 我的目标是将所有喜欢存储在一个表中,以使喜欢系统动态化,并且我希望能够根据喜欢模型键的不同组合将每个喜欢的项目包含在内 目标: 根据 user.id、like.itemId 和 like.type 获取用户的所有点赞,并将每个项目包含到点赞对象中

最佳答案

您可以使用条件数组解构来执行此操作。

Like.findAll({
    where: {userId: userId},
    include: [
        ...(type === 'Sedan' && [{ model: Sedan, required: true }]),
        ...(type === 'Truck' && [{ model: Sedan, required: true }]),
        ...(type === 'Van' && [{ model: Sedan, required: true }])
    ]
})

如果 type === 'Sedan' 它将解构数组并将对象 { model: Sedan, required: true } 返回到您的“include”数组.

<小时/>

或者,您可以将您的喜好设置为链接表:

User = [{
  id: 1,
  name: 'John',
  ...
}]

Vehicle = [{
  id: 1,
  type: 'Sedan',
  ...
}]

Likes = [{
  userId: 1,
  vehicleId: 1,
  likedAt: '2020-01-30'
}]

关于node.js - Sequelize : Use multiple keys from source to include target model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59989245/

相关文章:

node.js - 使用数组填充参数 - 初学者

jestjs - 为什么 done 在 sequelize 上的 supertest 请求之前运行得更早?

postgresql - 使用 PostgreSQL : "SQLSTATE[42P01]: Undefined table: 7 ERROR: the relation does not exist" 的 Doctrine2 ManyToMany 关系

postgresql - Clojure - Postgres 找不到合适的驱动程序

postgresql - 如何获得外键模型以及模型。我尝试使用包含

mysql - 当 GraphQL 查询只需要返回对象的某些字段时,为什么 MySQL/Sequelize 执行全选查询?

javascript - 使 Socket.io 路径与 NGiNX proxy_pass 一起使用

javascript - 如何使用express.js和request.js从Amazon S3下载文件?

html - Sendgrid 发送不带嵌入代码的 html 电子邮件

sql - 在非不同索引上使用递归 cte 计算不同行