Using a raw SQL query with Sequelize ORM and literal - mysql

Using the Sequelize ORM I am trying to update the field level_id where this field has a foreign key to the field Level in another table called level_tbl.
select * from level_tbl;
+----------+----------+
| level_id | Level |
+----------+----------+
| 1 | Higher |
| 2 | Ordinary |
+----------+----------+
My update task looks like this, and as you can see I am trying to get a raw sql query to work as a literal with Sequelize.
//Update task
router.put("/task/:id", (req, res) => {
if (!req.body) {
res.status(400)
res.json({
error: "Bad Data....!"
})
} else {
Task.update({
Level: req.body.Level,
Level_id: [sequelize.literal("SELECT level_id FROM level_tbl WHERE Level = 'Ordinary'")],
Year: req.body.Year,
Question: req.body.Question,
Answer: req.body.Answer,
Topic: req.body.Topic,
Sub_topic: req.body.Sub_topic,
Question_type: req.body.Question_type,
Marks: req.body.Marks,
Question_number: req.body.Question_number,
Part: req.body.Part,
Sub_part: req.body.Sub_part
}, {
where: {
id: req.params.id
}
})
.then(() => {
res.send("Task Updated")
})
.error(err => res.send(err))
}
})
What would be the correct syntax for this line?
Level_id: [sequelize.literal("SELECT level_id FROM level_tbl WHERE Level = 'Ordinary'")],
The issue is that I already have imported a model and have access to the global Sequelize instance. Therefore example in the documentation don't apply this way, i.e.,
order: sequelize.literal('max(age) DESC')
From https://sequelize.org/master/manual/querying.html
and also,
https://github.com/sequelize/sequelize/issues/9410#issuecomment-387141567
My Task.js where the model is defined is as follows,
const Sequelize = require("sequelize")
const db = require("../database/db.js")
module.exports = db.sequelize.define(
"physics_tbls", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
Level: {
type: Sequelize.STRING
},
Level_id: {
type: Sequelize.INTEGER
},
Year: {
type: Sequelize.INTEGER
},
.........
}, {
timestamps: false
}
)
I am using a MEVN stack -> MySQL, Express.js, Vue.js and Node.js
Any help would be greatly appreciated,
Thanks,

I needed to require Sequelize again in tasks.js, the file the defines the express routes. It wasn't enough just to require Task.js although Task.js does itself require sequelize.
const Sequelize = require('sequelize')
var express = require("express")
var router = express.Router()
const Task = require("../model/Task")
Also brackets needed around the query and inside the double quotes,
Level_id: Sequelize.literal("(SELECT level_id FROM level_tbl WHERE Level = 'Higher')"),

i'm using sequelize 6.3 and raw query on where is no longer supported, i'm using this syntax :
where: sequelize.where(sequelize.col("table.column"), "=", "yourvalue")
and it worked

Related

Typescript nested dynamic properties

I've been trying to improve the types of an older project that uses a lot of 'any' whenever things get complicated.
Replit-link
Consider the following irregular data structure where Data is an interface matching the example (some are nested objects, some are not. I use the same mapping function on all pages, depending on what is present in localData):
const data: Data = {
car: { name: 'x', speed: 45},
cat: { fur: true },
random: ['hi', 'bye']
why: "because"
};
Now I'm mapping this data on different pages like so
const nestedKey = 'car';
const localData = {
name: '',
speed: 0
};
Object.keys(localData).forEach(key => {
if (nestedKey && data[nestedKey]) {
// Here I'm not too sure what type to give key to make TS happy
localData[key] = data[nestedKey as keyof Data][key]
} else {
localData[key] = data[key as keyof Data]
}
});
const nestedKey: keyof typeof data = 'car';
keyof typeof data will return this literal type:
'car' | 'cat' | 'random' | 'why'
Which you could consume it like:
localData[key] = data[nestedKey][key]

SequelizeEagerLoadingError while include: [{model: , as: ' ' }]

I want to run this function. I want that the included model: SurveyResult getting an alias.
But i get this error: SequelizeEagerLoadingError: SurveyResult is associated to User using an alias. You've included an alias (Geburtsdatum), but it does not match the alias defined in your association.
const mediImport = await User.findAll({
where: { Id: 1 },
// Select forename as Vorname, name as Nachname
attributes: [['forename', 'Vorname'], ['name', 'Nachname']],
include: [{
model: SurveyResult,
as: 'Geburtsdatum'
}]
})
I know that it is a Problem with my associates, but i cant find the problem
Here are my models.
Model: User
User.associate = function (models) {
User.hasOne(models.Admin)
User.hasOne(models.UserStatus)
User.hasOne(models.SurveyResult, {
})
Model SurveyResult
SurveyResult.associate = function (models) {
SurveyResult.hasOne(models.Survey)
User.hasOne(models.SurveyResult, {})
You need to define the alias on the association level also , like this :
User.hasOne(models.SurveyResult,{ as : 'Geburtsdatum' });

BookShelf orm MySQL how to select column1-column2 as alias

In a raw MySQL query, I have something like this:
Select total_sales - over_head_costs As net_sales from departments;
How can I realize the same thing with BookShelf /knex query? Ideally not using knex.raw.
My attempt involves following:
let Department = bookshelf.Model.extend({
tableName: 'departments',
idAttribute: 'department_id',
},{
getDepartments: function(){
return this.fetchAll({columns: ['department_id', 'department_name', 'over_head_costs', 'total_sales - over_head_costs AS net_sales']})
.then(models=>models.toJSON());
},
});
Bookshelf does not have this feature but it brings a plugin for that: Virtuals
. No need to install anything, you just load it right after loading Bookshelf using bookshelf.plugin('virtuals').
Your model should then look like:
const Department = bookshelf.Model.extend({
tableName: 'departments',
idAttribute: 'department_id',
virtuals: {
net_sales: function() {
return this.get('total_sales') - this.get('over_head_costs');
}
}
},{
getDepartments: function(){
return this.fetchAll({columns: ['department_id', 'department_name', 'over_head_costs', 'net_sales']})
.then(models=>models.toJSON());
},
});

Subquery the same table : Sequelize

I have got a scenario where I would want the below query executed using sequelize.
select * from master where catg_level = 1 and obj_id in (select obj_id from master where catg_level = 2) order by position;
I've the below code written in sequelize.
Master.all({
where: {catg_level: '1'},
order: 'position ASC',
include: [{
model: Master,
as: 'sub-menu',
where: {catg_level: '2'}
}]
})
.then(function(a){
try {
console.log(JSON.stringify(a));
} catch (e) {
console.log(e);
}
});
The SQL generated this
The condition catg_level = 2 is added to the main query instead of being added as a subquery. I understand this is the actual functioning. But is there a workaround to get this done? Please advise.
Thanks in advance.
You can use sequelize.literal:
{
where: {
catg_level: '1',
obj_id:{
in:[sequelize.literal('(select obj_id from master where catg_level = 2)')]
}
},
order: 'position ASC',
}

Sails js sort by populated field

I need to sort data from a MySQL database on related table row.
Suppose we have two models:
ModelOne:
module.exports = {
tableName: 'modelOne',
attributes: {
// some atributes.........
modelTwo{
model: 'ModelTwo',
columnName: 'model_two_id'
}
}
}
ModelTwo:
module.exports = {
tableName: 'modelTwo',
attributes: {
// some atributes.........
model_two_id: {
type: 'integer',
autoIncrement: true,
primaryKey: true
},
name: 'string'
}
}
I would like to do something like:
ModelOne
.find(find_criteria)
.populateAll()
.paginate({page: page, limit: limit})
.sort('modelTwo.name')
.then(...)
Is there possibility to do this or I need to write an SQL query without using Waterline functions?
This is how I do it...
ModelOne
.find(find_criteria)
.populate('modelTwo', {sort: 'name ASC'})
.paginate({page: page, limit: limit})
.then(...)
As you can see, you can pass {sort} object to populate method.
No. Deep-population-sorting is on future list https://github.com/balderdashy/waterline/issues/266