Skip to content

Instantly share code, notes, and snippets.

View vonvick's full-sized avatar

Victor Nwaiwu vonvick

View GitHub Profile
@vonvick
vonvick / index.js
Created February 6, 2019 17:30
Sample model index file
require('dotenv').config();
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const config = require('<path-to-sequelize-config>');
const db = {};
const sequelize = new Sequelize(config.url, config);
@vonvick
vonvick / raw-queries-3.example.js
Created February 6, 2019 17:29
another example of raw queries
cars = await db.sequelize.query('SELECT "id" FROM Cars WHERE "Cars"."ownerId" = ?', {
replacements: ['active'], type: sequelize.QueryTypes.SELECT
});
@vonvick
vonvick / raw-queries-2.example.js
Created February 6, 2019 17:27
sequelize option property
// passing the model type to return the result as the instance of the model
currentMonthEarnings = await db.sequelize.query('SELECT SUM("priceEstimate") FROM "Orders" WHERE "assignedCarId" IN(:ids) AND "createdAt" < (:createdDate)', {
replacements: {ids: carIds, createdDate: currentDateMonth},
model: db.Order,
mapToModel: true
});
@vonvick
vonvick / raw-queries.example.js
Last active October 10, 2023 10:12
Raw SQL queries in Sequelize ORM for express.js
import db from '../../models';
import moment from 'moment';
const getAllUserEarnings = async (req, res) => {
// get the beginning of the current month
const currentDateMonth = moment().startOf('month').format();
let cars, carIds, totalEarnings, currentMonthEarnings;
// Use raw SQL queries to select all cars which belongs to the user
cars = await db.sequelize.query('SELECT "id" FROM Cars" WHERE "Cars"."ownerId" = (:id)', {