[英]load items where relation is null in 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 個用戶每個都有一個任務,我只想加載沒有任務的最后一個用戶。 這在續集中有可能嗎?
經過多次調試,我找到了解決方案
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,
},
我只能加載沒有任務的用戶
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.