【问题标题】:Sequelize: Use multiple keys from source to include target modelSequelize:使用源中的多个键来包含目标模型
【发布时间】:2020-01-30 15:23:46
【问题描述】:

我有一个类似的模型,它存储了喜欢项目的 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 db 中,id 从 1 开始并且只是递增,所以一个轿车.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'}

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

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

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

但我似乎找不到与项目类型相关的方法。

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

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    您可以使用条件数组解构来做到这一点。

    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 } 返回到您的“包含”数组。


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

    User = [{
      id: 1,
      name: 'John',
      ...
    }]
    
    Vehicle = [{
      id: 1,
      type: 'Sedan',
      ...
    }]
    
    Likes = [{
      userId: 1,
      vehicleId: 1,
      likedAt: '2020-01-30'
    }]
    

    【讨论】:

    • 你从哪里得到类型,当我这样做时,我得到“类型未定义”
    • 只需在.findAll 之外定义类型。 IE。 const type = '轿车'
    • 类型来自findAll,类型是like模型的一部分,每种返回的like都不同
    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    相关资源
    最近更新 更多