Model
Models represent tables in the database and are responsible for interacting with data.
INFO
Models are organized in the src/models directory.
Laratype is based on the TypeORM ORM to provide powerful features for data management, including methods to create, read, update, and delete (CRUD) data.
Creating Model
Generate Model
$ npx sauf make:model User$ pnpx sauf make:model User$ bunx sauf make:model UserLaratype will create a new model file in the src/models/ directory with the name User.ts.
TIP
You can create multiple models at once by passing multiple names.
See more
$ npx sauf make:model User Post$ pnpx sauf make:model User Post$ bunx sauf make:model User PostWriting Model
import { Column, Entity, Model, PrimaryGeneratedColumn } from "@laratype/database"
@Entity()
export class User extends Model {
@PrimaryGeneratedColumn()
id: number
@Column({ unique: true })
email: string
@Column({ select: false })
password: string
@Column()
firstName: string
@Column()
lastName: string
@Column()
age: number
static readonly fillable = [
'email',
'password',
'firstName',
'lastName',
'age',
]
}IMPORTANT
Each model must inherit from Laratype's Model class. After defining the model, Laratype will not automatically sync with the database. You need to run the sauf db:init command to apply the changes, see more in the Command section.
Mass Assignment
The fillable property defines fields that can be mass assigned. This helps protect against unwanted mass assignment attacks.
static readonly fillable = [
'name',
'age',
]User.save({
name: "John Doe",
age: 30,
isAdmin: true, // Will be ignored because it's not in fillable
});Password Hashing
By default, Laratype will automatically hash passwords when you use the findOneBy, save, or create methods, and automatically remove the password field when you use the findOne method.
Casting coming soon
Casting will be added in upcoming updates.
Command
After creating the model, you need to run the following command to sync changes with the database:
Development
$ npx sauf db:init$ pnpx sauf db:init$ bunx sauf db:initProduction
$ npm run saufx db:init$ pnpm saufx db:init$ bun run saufx db:init