Created
June 23, 2017 12:45
-
-
Save DoumanAsh/f869ecbbac1645d992dc2336e939cae2 to your computer and use it in GitHub Desktop.
Example of getting raw data from rows with many-to-many associations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Sequelize = require('sequelize') | |
const username = "user" | |
const password = "pass" | |
const dialect = 'sqlite' | |
const sequelize = new Sequelize('test', username, password, { | |
dialect, | |
pool: { | |
max: 5, | |
min: 0, | |
idle: 10000 | |
}, | |
}); | |
let clients = { | |
id: { | |
type: Sequelize.INTEGER, | |
primaryKey: true, | |
autoIncrement: true | |
}, | |
login: { | |
type: Sequelize.STRING(20), | |
unique: true, | |
allowNull: false, | |
}, | |
password: { | |
type: Sequelize.STRING(20), | |
allowNull: false | |
}, | |
name: { | |
type: Sequelize.TEXT, | |
allowNull: false | |
}, | |
address: { | |
type: Sequelize.TEXT, | |
allowNull: false | |
}, | |
email: { | |
type: Sequelize.TEXT, | |
allowNull: false, | |
validate: { | |
isEmail: true | |
} | |
}, | |
materials_version: Sequelize.INTEGER, | |
prices_version: Sequelize.INTEGER | |
} | |
let orders ={ | |
number: { | |
type: Sequelize.INTEGER, | |
primaryKey: true, | |
autoIncrement: true | |
}, | |
text: Sequelize.TEXT | |
} | |
clients = sequelize.define('clients', clients) | |
orders = sequelize.define('orders', orders) | |
let order = { | |
text: "I want something" | |
} | |
let client = { | |
login: "Client1", | |
password: "Password1", | |
name: "Client's name", | |
address: "Client's address", | |
email: "client@mail.com", | |
materials_version: 1, | |
prices_version: 2 | |
} | |
let client2 = { | |
login: "Client2", | |
password: "Password2", | |
name: "Client's name2", | |
address: "Client's address2", | |
email: "client2@mail.com", | |
materials_version: 1, | |
prices_version: 2 | |
} | |
async function do_stuff() { | |
const find_all_opts = { | |
raw: true, | |
attributes: { | |
exclude: ['createdAt', 'updatedAt'] | |
} | |
} | |
await orders.belongsToMany(clients, {through: "OrdersClients"}) | |
await clients.belongsToMany(orders, {through: "ClientsOrders"}) | |
await sequelize.sync() | |
order = await orders.create(order) | |
client = await clients.create(client) | |
client2 = await clients.create(client2) | |
await client.setOrders([order]) | |
await client2.setOrders([order]) | |
result = await clients.findAll(find_all_opts) | |
console.log(result) | |
} | |
do_stuff() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment