我有一个函数,它必须返回包含域事件的配置。
async function getConfig(configId, country) {
return await db.config.findOne({
where: { id: configId },
include: [
{
model: db.domain,
attributes: ['id', 'domain'],
where: {
isActive: true,
},
},
],
});
}
但是我收到错误 default - TypeError: Cannot read property 'dataValues' of undefined
因为我的表 domain
是空的但我想得到结果 "result": {
"id": 4,
"country": "US",
"domains": []
}
我该怎么做?配置模型
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Config extends Model {
/**
* Helper method for defining associations.
* This method is not a part of DataTypes lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
Config.hasMany(models.domain, {
foreignKey: 'configId',
onDelete: 'CASCADE',
});
}
}
Config.init(
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
country: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
sequelize,
tableName: 'configs',
modelName: 'config',
timestamps: false,
},
);
return Config;
};
领域模型const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Domain extends Model {
/**
* Helper method for defining associations.
* This method is not a part of DataTypes lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
Domain.belongsTo(models.config, {
foreignKey: 'configId',
});
}
}
Domain.init(
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
domain: {
type: DataTypes.STRING,
allowNull: false,
},
isActive: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
},
{
sequelize,
tableName: 'domains',
modelName: 'domain',
timestamps: false,
},
);
return Domain;
};
最佳答案
您只需要像这样指示 required: false
选项:
return await db.config.findOne({
where: { id: configId },
include: [
{
required: false,
model: db.domain,
attributes: ['id', 'domain'],
where: {
isActive: true,
},
},
],
});
这样你就对 Sequelize 说你希望获得主模型实例,而不管关联模型中的条件如何。如果您熟悉 SQL,则意味着将
INNER JOIN
转换为 LEFT OUTER JOIN
。
关于sequelize.js - Sequelize findOne 返回 null 然后模型为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65093503/