在sequelize中加载关系为null的项目

时间:2017-12-28 10:28:18

标签: node.js sequelize.js

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

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

如果我有三个用户,其中两个用户各有一个任务,我想只加载没有任务的最后一个用户。这可能是续集吗?

1 个答案:

答案 0 :(得分:1)

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

<?php 
    $qty_n_day = '1/2,3/6';
    $qty_day = explode(',',  $qty_n_day);

    $days = [];
    foreach ($qty_day as $day) {
        if (($res = explode('/', $day))) {
            $days[$res[1]] = $res[0];
        }
    }
    /*
    the array should stay like this
    $days = [
        2 => 1,
        6 => 3
    ];
    */

    for($i = 1; $i<=31;$i++){ 
        if (isset($days[$i])) { // if the key exists set the value
            echo '<td>' . $days[$i] . '</td>';
        } else {
            echo '<td>-</td>';
        }
    }

?>

添加此where子句

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

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