Creating a Model
Creating a User Model
To create the simplest User class, you should first define the Users model. Here is an example code to create such a model:
import {
Boolean,
Column,
PrimaryGeneratedColumn,
String,
Table
} from "@myroslavshymon/orm";
@Table({name: 'users'})
export class Users {
@PrimaryGeneratedColumn({type: 'BIGINT'})
user_id: number;
@String({type: "VARCHAR", length: 255})
@Column({options: {unique: true, nullable: false}})
username: string;
@String({type: "VARCHAR", length: 255})
@Column({options: {nullable: false}})
email: string;
@String({type: "VARCHAR", length: 255})
@Column({options: {nullable: false}})
password: string;
@Column({options: {dataType: 'BOOLEAN', defaultValue: false}})
is_active: boolean;
}Пояснення:
@Table({name: 'users'}): Specifies that this model will be stored in a named tableusers.@PrimaryGeneratedColumn({type: 'BIGINT'}): Declares a fielduser_idas the primary key of the typeBIGINT, which is automatically generated.@String({type: "VARCHAR", length: 255}): Defines a fieldusernameas a string up to 255 characters long, with unique values and mandatory.@Column({options: {nullable: false}}): Indicates that fieldsemailandpasswordare requeired.@Column({options: {dataType: 'BOOLEAN', defaultValue: false}}): Declares a fieldis_activeas a boolean with a default valuefalse.
Додавання Моделі до Системи
After creating the model, you need to add it to the database configuration in your ORM system. This is done by including the model in the models array when initializing the database manager:
import { DatabaseManager, DatabasesTypes, DataSourceContext } from "@myroslavshymon/orm";
import { Users } from "./models/users"; // шлях до моделі
export const databaseManager = new DatabaseManager<DatabasesTypes.POSTGRES>(
{
type: DatabasesTypes.POSTGRES,
host: 'localhost',
user: 'postgres',
password: 'xxx',
port: 5432,
database: 'first',
models: [
Users
],
},
new DataSourceContext()
);Creating a Table in the Database
To create the users table in the database, follow these steps:
Initialize the database connection using
createOrmConnection().Run
npm run startto synchronize theUsersclass and map it incurrent_database_ingotin themigrationstable for subsequent migration creation.
Last updated