本文介绍了在续集中加载关系为空的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是续集的新手,我正在尝试加载我的用户表中任务关系为空的所有条目.但它不工作.这是我尝试过的:
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');
});
如果我有 3 个用户,其中 2 个用户各有一个任务,我想只加载最后一个没有任务的用户.这在sequelize中可能吗?
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);
});
});
通过添加这个 where 子句
by adding this where clause
where: {
'$Task$': null,
},
我只能加载没有任务的用户
i was able to load only users without a task
这篇关于在续集中加载关系为空的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!