【问题标题】:Nodejs SequelizeNodejs 续集
【发布时间】:2023-01-30 13:52:23
【问题描述】:

我有这两个型号:

  1. 订购型号
  2. 解决方案模型

    订单模型

    'use strict';
    const { Model } = require('sequelize');
    module.exports = (sequelize, DataTypes) => {
        class Orders extends Model {
            /**
             * Helper method for defining associations.
             * This method is not a part of Sequelize lifecycle.
             * The `models/index` file will call this method automatically.
             */
            static associate(models) {
                // define association here
                Orders.hasMany(models.Payments, {
                    foreignKey: {
                        name: 'order',
                        allowNull: false,
                    },
                    constraints: false,
                    onDelete: 'cascade',
                });
    
                Orders.hasOne(models.Solutions, {
                    foreignKey: {
                        name: 'order',
                        allowNull: false,
                    },
                    constraints: false,
                    onDelete: 'cascade',
                    as: "solution"
    
                });
            }
        }
        Orders.init(
            {
                order_no: {
                    defaultValue: DataTypes.UUIDV4,
                    type: DataTypes.UUID,
                    primaryKey: true,
                    allowNull: false,
                    unique: true,
                },
                order_date: {
                    type: DataTypes.DATE,
                    defaultValue: DataTypes.NOW,
                },
                
                title: {
                    type: DataTypes.STRING,
                    allowNull: false,
                },
            },
            {
                sequelize,
                modelName: 'Orders',
                tableName: 'Orders',
            }
        );
        return Orders;
    };
    

    #2。解决方案表

    
    'use strict';
    const { Model } = require('sequelize');
    module.exports = (sequelize, DataTypes) => {
        class Solutions extends Model {
            /**
             * Helper method for defining associations.
             * This method is not a part of Sequelize lifecycle.
             * The `models/index` file will call this method automatically.
             */
            static associate(models) {
                // define association here
    
                Solutions.belongsTo(models.Orders, {
                    foreignKey: 'order',
                    onDelete: 'cascade',
                    constraints: false,
                    as: "solution"
                });
            }
        }
        Solutions.init(
            {
                solutionId: {
                    defaultValue: DataTypes.UUIDV4,
                    type: DataTypes.UUID,
                    primaryKey: true,
                    allowNull: false,
                    unique: true,
                },
    
                content: {
                    type: DataTypes.TEXT,
                    allowNull: false,
                },
                additional_instruction: {
                    type: DataTypes.TEXT,
                    allowNull: true,
                },
                date_submited: {
                    type: DataTypes.DATE,
                    defaultValue: DataTypes.NOW,
                },
            },
            {
                sequelize,
                modelName: 'Solutions',
            }
        );
        return Solutions;
    };
    

    我正在尝试获取解决方案尚未提交到解决方案表的所有订单,即订单字段(解决方案表中的外键)为空。

    我试过这个

    Orders.findAndCountAll({
            include: [
                {
                    model: Users,
                    attributes: ['username', 'email', 'uid'],
                },
                {
                    model: Solutions,
                    as: "solution",
                    where: {
                        solutionId: {
                            [Op.notIn]: Solutions.findAll({
                                attributes: ['solutionId']
                            })
                        }
                    }
                }
            ],
            offset: page,
            limit,
        })
    

    我期望得到一个列表,其中包含未添加解决方案表中的解决方案的所有订单。我对续集有点陌生。

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    您可以尝试在 left join 之后进行过滤,Sequelize 可以直接在 join 上或 after join 应用 where 子句。

    Orders.findAndCountAll({
      where: {
        '$orders.solution$': null,
      },
      include: [
        {
          model: Solutions,
          as: "solution",
          required: false
        },
      ],
    })
    

    在 SQL 中就像:

    SELECT COUNT(*) 
    FROM orders o 
    LEFT JOIN solutions s ON o.id = s.order AND s.order IS NULL
    

    VS

    SELECT COUNT(*) 
    FROM orders o 
    LEFT JOIN solutions s ON o.id = s.order 
    WHERE s IS NULL
    

    【讨论】:

      【解决方案2】:

      如果 order 不退出,您可以使用过滤器执行左连接,该过滤器从 Solutions 表中排除记录。

      Orders.findAndCountAll({
              include: [
                  {
                      model: Users,
                      attributes: ['username', 'email', 'uid'],
                  },
                  {
                      model: Solutions,
                      as: "solution",
                      required: false,                  
                  },
              ],
              where: {
                '$solution.order$': null
              }, 
              offset: page,
              limit,
          })
      

      【讨论】:

      • 我在这里遇到错误。 errno: 1064, sqlState: '42000', sqlMessage: "你的 SQL 语法有错误;请查看与你的 MariaDB 服务器版本对应的手册,了解在第 1 行的 'order IS NULL' 附近使用的正确语法",sql : 'SELECT count(Orders.order_no) AS count FROM Orders AS Orders LEFT OUTER JOIN Solutions AS solution ON Orders.@987654337@6@46.387@46.38 @AND order IS NULL;', 参数:未定义
      • 我注意到它不起作用,它在过滤时忽略了该字段。当我向该端点发送一个获取请求时,它得到的是字段解决方案(别名为订单)为空的订单,但在表中该字段实际上有一个值。当我删除 include 部分中的过滤器时,我得到这些字段的订单具有相关表的 json 表示而不是 null。
      • 这是您查询的输出 ``` { User: { username: "Morph", email: "myemail@gmail.com", uid: "166a4eba-7f00-4f35-8ef8-7fad7600ae99" }, deadline: "1970- 01-01T00:00:00.000Z", order_date: "2023-01-28T08:34:44.000Z", order_no: "02e01ecf-08bb-40d4-8697-bcffe416db32", 所有者: "166a4eba-7f00-4f35-8ef8- 7fad7600ae99", solution: null, title: "Metaverse", } ``` 但解决方案不为空。
      猜你喜欢
      • 1970-01-01
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 2018-06-15
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多