node.js - 加载sequelize中关系为空的项目

标签 node.js sequelize.js

我是 Sequelize 新手,我正在尝试加载用户表中任务关系为空的所有条目。但它不起作用。这是我尝试过的:

const express = require('express');
const app = express();

const Sequelize = require('sequelize');
const sequelize = new Sequelize('sequelize', 'mazinoukah', 'solomon1', {
  host: 'localhost',
  dialect: 'postgres',

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000,
  },
});

const Task = sequelize.define('Task', {
  name: Sequelize.STRING,
  completed: Sequelize.BOOLEAN,
  UserId: {
    type: Sequelize.INTEGER,
    references: {
      model: 'Users', // Can be both a string representing the table name, or a reference to the model
      key: 'id',
    },
  },
});

const User = sequelize.define('User', {
  firstName: Sequelize.STRING,
  lastName: Sequelize.STRING,
  email: Sequelize.STRING,
  TaskId: {
    type: Sequelize.INTEGER,
    references: {
      model: 'Tasks', // Can be both a string representing the table name, or a reference to the model
      key: 'id',
    },
  },
});

User.hasOne(Task);
Task.belongsTo(User);

app.get('/users', (req, res) => {
  User.findAll({
    where: {
      Task: {
        [Sequelize.Op.eq]: null,
      },
    },
    include: [
      {
        model: Task,
      },
    ],
  }).then(function(todo) {
    res.json(todo);
  });
});

   app.listen(2000, () => {
      console.log('server started');
   });

如果我有三个用户,其中 2 个用户每个都有一个任务,我想只加载最后一个没有任务的用户。这在 Sequelize 中可能吗?

最佳答案

经过多次调试,我找到了解决方案

app.get('/users', (req, res) => {
User.findAll({
    where: {
      '$Task$': null,
    },
    include: [
      {
        model: Task,
        required: false,
      },
    ],
  }).then(function(todo) {
    res.json(todo);
  });
});

通过添加此 where 子句

where: {
  '$Task$': null,
},

我只能加载没有任务的用户

关于node.js - 加载sequelize中关系为空的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48005763/

相关文章:

javascript - 如何使用 sequelize 修复模型类的未定义问题?

mysql - db.sync({alter :true}). then(); 在 sequelize node.js express app

node.js - ORM错误NO_SUPPORT : Connection protocol not supported - have you installed the database driver for postgres?

node.js - 在 sequelize seeds 中查找记录

node.js - 从JavaScript客户端查询字符串查询

node.js - CORS预检 channel 未成功,React to Express

mysql - 如何在过滤元素时使sql查询显示每一行?

sequelize.js - Sequelize include 包含来自连接表的记录

angularjs - 响应状态为零的 Express Redis session 崩溃

javascript - 在Node js中读取多个文件并发送JSON数据