简体   繁体   中英

load items where relation is null in sequelize

I'm new to sequelize, i'm trying to load all entries in my user table where the task relation is null. but its not working. here is what i have tried:

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');
   });

if i have three users, and 2 of those users have a task each, i want to load just the last user without a task. is this possible in sequelize ?

after much debugging i found the solution

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

by adding this where clause

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

i was able to load only users without a task

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM