# Sequelize
---
## Sequelize is an ORM
AN ORM (Object Relational Mapping) is a progrmaming technique that is used to convert data bewtween systems using objects. In our case we will be using an ORM to interact with the a databse and its tables.
---
## Why use one.
Short Ans: Developers are LAZY!!!
Long Answer: Developers are LAAAAAAAAAZY!!!!
---
## More Seriously
```
- SQL Commands are hard to write
- Constantly wrting them will increase your chances of errors bc of its repetitive nature
- Context switching.
```
---
## What will we be learning
- How to use SQLize CLI
- How to use SQLize library
---
## Set up
```
npm i sequelize
npm i --save-dev sequelize-cli
```
---
## Initialize the Configuration
```
npx sequelize-cli init
```
---
## Understanding the initialization
```
//directories
- config: Edit database config
- migrations: Keeps track of changes made in the database. These changes are done with migration commands
- models: Schema. (Obejct that represents the databse table)
- seeders: Contains the data that will be inserted into DB.
```
---
# SQLize Library Usage
---
## Set up
```
const { Sequelize, DataTypes } = require('sequelize')
const sequelize = new Sequelize('xyz', '', '', {
host: 'localhost',
dialect: 'postgres'
});
```
---
## Models
Models are object representations of our database table. Sequelize will use this data to structure the table within out database.
---
## Define a model
We define a model using the `.define()` method within the library. The first parameter is the name of the table you want. the second param is an object containing the columns and data types
Note: The table name will automatically be pluralized upon creation. ex: User -> Users automatically
```
sequlize.define("Table_Name", {
name: DataTypes.TEXT,
age: DataTypes.INTEGER
});
```
---
## Sync-ing models
Syncing out models will allow us to create the database table.
```
const Table = sequlize.define("Table_Name", {
name: DataTypes.TEXT,
age: DataTypes.INTEGER
}).sync()
```
*NOTE: you can also sync tables on connection*
---
## Sync-ing models on connection
Syncing out models will allow us to create the database table.
```
try {
await this.sequelize.sync({ force: true, logging: console.log });
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
```
---
## Sequelize CRUD
```
.create()
.findAll()
.findByPk()
.update()
.destroy()
```
[CRUD Documentaion](https://sequelize.org/docs/v6/core-concepts/model-querying-basics/)
---
{"metaMigratedAt":"2023-06-17T03:18:19.921Z","metaMigratedFrom":"Content","title":"Sequelize","breaks":true,"contributors":"[{\"id\":\"5e29e175-4809-4add-a41e-e8982dab52a9\",\"add\":2705,\"del\":72}]"}