I have an Article
Sequelize model where articles relate to each other. Some articles are translated copies of other articles. The relation is setup like so:
var Article = sequelize.define('Article', { type : DataTypes.ENUM('source', 'translated'), sourceArticleId : DataTypes.INTEGER }); db.Article.hasMany(db.Article, { foreignKey: 'sourceArticleId', as : 'TranslatedArticles' });
So, an article with type = 'source'
can have many translatedArticles
where type = 'translated'
.
Now, I want to query all source
articles that do not have a translation.
Based on an issue at the Sequelize project github, this would be accomplished like so:
Article.findOne({ where: Sequelize.literal('translatedArticles.sourceArticleId IS NULL'), include: [ { model: Article, as : 'TranslatedArticles' } ] });
Yet when I run this I get:
SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'translatedArticles.sourceArticleId' in 'where clause'
I've also tried variations in naming, including TranslatedArticles.sourceArticleId
, articles.sourceArticleId
, and Articles.sourceArticleId
.
Am I missing something?
Note that I temporarily work around this problem by using a literal NOT EXISTS query, like so:
Article.findOne({ where: Sequelize.literal('NOT EXISTS (SELECT id FROM Articles WHERE Article.id = Articles.sourceArticleId LIMIT 1)') });
The Not equal Operator use for filter data those value available in your table. In sql we use not equal to sign ( != ) but in sequelize we use Op.ne in query like below example.
Sequelize Model. count() method is used to generate and execute a SELECT COUNT SQL query to your connected database. The method accepts an object of options that you can define to modify the generated query. You need to create a Sequelize Model for the above table and call the count() method from there.
To set the Sequelize findAll sort order in Node. js, we can set the order property. const getStaticCompanies = () => { return Company. findAll({ where: { //... }, order: [ ['id', 'DESC'], ['name', 'ASC'], ], attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'] }); };
I don't know what database technology you are using on the backend but I am guessing it is case-sensitive. I believe it isn't finding the field because you need to capitalize the t in translatedArticles. This should work:
Article.findOne({ where: Sequelize.literal('TranslatedArticles.sourceArticleId IS NULL'), include: [ { model: Article, as : 'TranslatedArticles' } ] });
mabe i have find the solution, use subQuery: false
, this option don't have in documentation.
Article.findOne({ subQuery: false, where: Sequelize.literal('translatedArticles.sourceArticleId IS NULL'), include: [ { model: Article, as : 'TranslatedArticles' } ] });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With