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
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},
]
})
}
I want to join 2 tables and want to show latest post first based on current date for example today's publish post will show at top then future date then past date's post will show. I need to write this query in sequelize. I am getting unknown column error 'postModel.DATE(published_at)' My sequelize query is like that -
postModel.findAndCountAll({
include:[
{ model:userModel,
where: { user_id: user_id},
required:false
},
],
order: [
[ 'DATE(published_at) = DATE(NOW())', 'DESC']
],
limit: limit,
offset: offset,
});
Following raw query is working well to me
SELECT * FROM posts as P JOIN user as U ON U.id = P.user_id
where
ORDER BY
DATE(P.published_at)=DATE(NOW()) DESC,
DATE(P.published_at)<DATE(NOW()) DESC,
DATE(P.published_at)>DATE(NOW()) ASC`
remove your date function and query like this .
postModel.findAndCountAll({
include: [{ model: userModel, where: { user_id: user_id },required:false }],
where: {
published_at: {
[Op.eq]: Date(NOW()),
},
},
order: [["published_at", "DESC"]],
limit: limit,
offset: offset,
});
I am using below query on my code that is
await to( mymodel.aggregate('cid', 'DISTINCT', {plain: false,where:{created_by:user.id}}));
and query out put on console is
SELECT DISTINCT(`cid`) AS `DISTINCT` FROM `mymodel` AS `mymodel` WHERE `mymodel`.`created_by` = 7;
I got below output that is
ids --------------- [ { DISTINCT: 9 }, { DISTINCT: 10 }, { DISTINCT: 11 } ]
I want to change the alias that is DISTINCT to id. How i do that like below
ids --------------- [ { id: 9 }, { id: 10 }, { id: 11 } ]
I don't think .aggregate() supports aliasing fields however it's simple to turn this into a regular query instead.
await mymodel.findAll({
attributes: [ [ Sequelize.fn('DISTINCT', 'cid'), 'id' ] ],
where: { created_by: user.id }
});
Here we're utilising Sequelize.fn() to create the DISTINCT on cid and using the array attribute notation to alias it to id. More info on this here.
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"});
});