Maz*_*kah 5 node.js sequelize.js
我是续集的新手,我正在尝试加载用户表中任务关系为空的所有条目。但它不起作用。这是我尝试过的:
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');
});
Run Code Online (Sandbox Code Playgroud)
如果我有三个用户,其中两个用户每个都有一个任务,我想只加载最后一个没有任务的用户。这在续集中可能吗?
经过多次调试我找到了解决方案
app.get('/users', (req, res) => {
User.findAll({
where: {
'$Task$': null,
},
include: [
{
model: Task,
required: false,
},
],
}).then(function(todo) {
res.json(todo);
});
});
Run Code Online (Sandbox Code Playgroud)
通过添加此 where 子句
where: {
'$Task$': null,
},
Run Code Online (Sandbox Code Playgroud)
我只能加载没有任务的用户
| 归档时间: |
|
| 查看次数: |
3144 次 |
| 最近记录: |