I need to sequelize raw query change to sequelize ORM
This is my query
db.sequelize.query("SELECT count(*) as count FROM cubbersclosure WHERE CAST('"+ fromDate +"' as date) <= toDate AND CAST('"+ toDate +"' as date) >= fromDate", { type: sequelize.QueryTypes.SELECT}).then(closureData=>{
res.send(closureData);
}).catch(error=>{
res.status(403).send({status: 'error', resCode:200, msg:'Internal Server Error...!', data:error});
});
Change to like this
CubbersClosure.findAndCountAll({
where:{
// condtion here
}
}).then(closureData=>{
res.send(closureData);
}).catch(error=>{
res.status(403).send({status: 'error', resCode:200, msg:'Internal Server Error...!', data:error});
});
try this condition:
where: {
toDate: { $gte: sequelize.cast(req.body.toDate, 'date') },
fromDate: { $gte: sequelize.cast(req.body.fromDate, 'date') },
},
Related
I have a mysql Query:-
SELECT #a:=#a+1 serial_number,rule FROM pledges,(SELECT #a:= 0) AS a;
This gives me a serial number along with the rule from the table.
How can I do that in Sequelize?
This is the query I wrote in the model which gives me id and rule:-
Pledge.getPledgeList = function(lang_code='EN') {
return this.findAll({
attributes:['id','rule'],
where: {
status:'a',
deleted_at:null
},
include:[
{ association: 'local', where: {lang_code:lang_code} ,required: false},
]
})
}
SELECT * FROM `EVENT` WHERE MONTH(START_DATE) = 7 AND YEAR(START_DATE) = 2019
How to use this query in sequelize with nodejs?
You can use range operators such as $gte, $lte, $gt, $lt:
model.findAll({
where: {
start_date: {
'$gte': new Date("2019-07-01")
}
}
})
If I execute the following sequence code sequelize
models.Venta.sum(
'total'
, {
where: {
fechaExpedicion: {
[Op.gte]: '2018-03-31 00:00:00',
[Op.lte]: '2018-03-31 23:59:59'
}
},
attributes: ['elaboradoPor'],
group: 'elaboradoPor'
,
logging: console.log
})
.then(totalIva => {
console.log(JSON.stringify(totalIva))
})
.catch(e=> {console.log(e)})
I see only the first result of the survey (with sequelize).
result sequelize code
With
logging: console.log
I get the SQL instruction for MariaDB:
SELECT elaboradoPor, sum(total) AS sum FROM Venta AS Venta WHERE (Venta.fechaExpedicion >= '2018-03-31 00:00:00' AND Venta.fechaExpedicion <= '2018-03-31 23:59:59') GROUP BY elaboradoPor;
If I execute, the select in HeidiSQL gives me the correct results.
Select HeidySQL
Please, what is missing in the sequelize instruction to obtain the best results?
I changed the instruction and used findall () and fn to build the sums and integrated additional operations.
models.Venta.findAll({
where: {
fechaExpedicion: {
[Op.gte]: '2018-03-31 00:00:00',
[Op.lte]: '2018-03-31 23:59:59'
}
},
logging: console.log,
attributes: [
'elaboradoPor',
[Sequelize.fn('SUM', Sequelize.col('total')), 'totalSuma'],
[Sequelize.fn('SUM', Sequelize.col('totalIva')), 'totalIva'],
[Sequelize.fn('SUM', Sequelize.col('saldo')), 'totalSaldo']
],
group: ['elaboradoPor']
})
.then(resultados => {
console.log(JSON.stringify(resultados))
})
.catch(e => { console.log(e)
})
La respuesta es: sequelize final
I need to execute this query using sequelize.
select * from mysqlDB.songTable where
X in (SELECT X FROM movieDB4.songTable where Y like('%pencil%') and Z='title') and
Y='tam' and Z='language';
I tried like this. but it throws some invalid value[object] error. please help to resolve this query.
const tempSQL = sequelize.dialect.QueryGenerator.selectQuery('songTable',{
attributes: ['X'],
where: {
Y: {$like: '%'+text[i]},
Z: "content_title"
}})
.slice(0,-1); // to remove the ';' from the end of the SQL
User.findAll({
where: {
X: {
$in: sequelize.literal('(' + tempSQL + ')'),
$and: {Y: lang.substring(0,3),
Z: 'language'}
}
}
})
You can use sequelize.query() to execute raw queries.
Example
return this.sequelize.query(`SELECT category_id, category_name from table_categories where category_id in (SELECT DISTINCT category_id from table_authorized_service_center_details where center_id in (SELECT center_id from table_authorized_service_center where brand_id ${condition}));`).then((results) => {
if (results.length === 0) {
reply({status: true, categories: [], forceUpdate: request.pre.forceUpdate});
} else {
reply({status: true, categories: results[0], forceUpdate: request.pre.forceUpdate});
}
}).catch((err) => {
console.log(err);
reply({status: false, message: "ISE"});
});
equivalent sequelize query for the following raw query:
SELECT
*,
(distance1 - table.distance) as distance
FROM
table
HAVING
distance >= 100;
Translation.findAll({
attributes: { include: [[models.sequelize.fn('LENGTH', models.sequelize.col('value')), 'total']] },
having: {total: {lte: 10}}
}).then(function(result) {
result.forEach(function(t) {
...
});
})
is equivalent to
SELECT *, LENGTH(`value`) AS `total`
FROM `content_translation`
HAVING `total` <= 10;
And works.
I think you should have somthing like
table.findAll({
attributes: { include: [['(distance1 - distance)', 'distance']] },
having: {distance: {gte: 10}}
}).then(function(result) {
result.forEach(function(t) {
...
});
})
http://docs.sequelizejs.com/en/latest/api/model/#findalloptions-promisearrayinstance