gpt4 book ai didi

javascript - SequelizeEagerLoadingError,无法使用包含获取数据

转载 作者:行者123 更新时间:2023-12-03 22:39:11 25 4
gpt4 key购买 nike

我使用 Sequelize.js 向数据库发出请求。我有两个表之间的多对多关系,我做了第三个连接表。这是我的三张 table 。 polit_in_article 是连接表。

政治家.js:

module.exports = (sequelize, DataTypes) => {
const Politician = sequelize.define('politician', {
...
});

Politician.associate = (models) => {
Politician.hasMany(models.Polit_in_article, {
foreignKey: 'politicianId',
as: 'polit_in_articles',
});
};

return Politician;
};

文章.js:
module.exports = (sequelize, DataTypes) => {
const Article = sequelize.define('article', {
...
});

Article.associate = (models) => {
Article.hasMany(models.Politician, {
foreignKey: 'articleId',
as: 'polit_in_articles'
});
};
return Article;
};

polit_in_article.js:
module.exports = (sequelize, DataTypes) => {
const Polit_in_article = sequelize.define('polit_in_article', {
times_mentioned: DataTypes.INTEGER,
});
Polit_in_article.associate = (models) => {
Polit_in_article.belongsTo(models.Article, {
// foreignKey: 'articleId',
as: 'articles',
});
Polit_in_article.belongsTo(models.Politician, {
// foreignKey: 'politicianId',
as: 'politicians',
});
};

return Polit_in_article;
};

这是我的 Controller (不确定这是否是正确的调用方式):
const Sequelize = require('sequelize');

const Article = require('../models').Article;
const Politician = require('../models').Politician;
const Polit_in_article = require('../models').Polit_in_article;

const Op = Sequelize.Op;

module.exports = {
getAllArticlesOfPolitician(req) {
return Article
.findAll({
include: [{
model: Polit_in_article,
include: [{
model: Politician,
where: {
lastname: req.query.politicianLastName,
}
}],
}],
}).then(response => response)
// .catch(err => err);
}
};

有了这个,我得到了一个错误 SequelizeEagerLoadingError: polit_in_article is not associated to article 。我可能错过了一些东西,但我真的不知道该怎么做。我试图使文章表具有关联 as: 'polit_in_articles' ,这一直有效,直到我需要将政治家表也包含在查询中。

最佳答案

您需要在关联中使用 through 关键字。 Articles 将有 politicians through Polit_in_article 模型,但是由于您只是在其上使用主键,因此您可以对其进行推断并省略 polit_in_article.js 并仅使用字符串来命名表。

Politician.associate = (models) => {
Politician.hasMany(models.Article, {
foreignKey: 'politicianId',
through: 'polit_in_article',
as: 'articles',
});
};

Article.associate = (models) => {
Article.hasMany(models.Politician, {
foreignKey: 'articleId',
through: 'polit_in_article',
as: 'politicians',
});
};

现在您可以通过指定 asthrough 来查询连接表。
getAllArticlesOfPolitician(req) {
return Article.findAll({
include: [{
model: Politician,
as: 'politicians',
through: 'polit_in_article',
where: {
lastname: req.query.politicianLastName,
},
}],
})
.then(response => response)
.catch(err => err);
}

关于javascript - SequelizeEagerLoadingError,无法使用包含获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52824222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com