-
Notifications
You must be signed in to change notification settings - Fork 0
Defining Models
Amaury edited this page Oct 10, 2021
·
8 revisions
Models are decorated with the @Entity decorator.
- options
- name: will set table property
- timestamps (optional): will set timestamps property
@Entity({
name: "articles",
timestamps: true,
})
export class Article extends DenoDB.Model {
// ...
}Columns are decorated with the Column Decorator.
@Column Takes the same options as described here.
- options
- type: string
- default (optional): unknown
- as (optional): string
- unique (optional): boolean
- autoIncrement (optional): boolean
- allowNull (optional): boolean
- precision (optional): number
- scale (optional): number
- values (optional): unknown[]
- comment (optional): string;
- primaryKey (optional): boolean
- length (optional): number
@Entity("articles")
export class Article extends DenoDB.Model {
@Column({
type: DenoDB.DataTypes.STRING,
default: "bonjour",
allowNull: true,
unique: true,
})
declare public name: string;
}Same as above, but primaryKey option is always true.
@Entity("articles")
export class Article extends DenoDB.Model {
...
@PrimaryColumn({ type: DenoDB.DataTypes.INTEGER, autoIncrement: true })
declare public id: number;
}Add @BelongsTo to relation property.
- arguments
- arg1 : The other Model
- arg2 : The inverse property name
- arg3 (optional) : foreignKey options
@Entity("comments")
export class Comment extends DenoDB.Model {
// Article equals the relation Model and "comments" is the inverse key of this model.
@BelongsTo(() => Article, "comments")
declare public static article: () => Promise<Article>;
}The inverse side will be automaticaly populated, you just have to declare in order to keep Type completion.
@Entity("articles")
export class Article extends DenoDB.Model {
// ...
declare public static comments: () => Promise<Comment[]>;
}The following code will be generated for the property :
function() {
return this.<OneToOne | ManyToMany | BelongsTo>(<inverseEntity>);
}You can override the default bahavior of the relation.
@Entity("articles")
export class Article extends DenoDB.Model {
// ...
public static comments() {
console.log("fetching relation");
return this.hasMany(Comment);
}
}@Entity("users")
export class User extends DenoDB.Model {
@OneToOne(() => File, "userAvatar")
declare public static avatar: () => Promise<File>;
}@Entity("files")
export class File extends DenoDB.Model {
declare public static userAvatar: () => Promise<User>;
}NOTE : There is actually no way to get the generated Pivot table, it will be done in future release.
@Entity("users")
export class User extends DenoDB.Model {
@ManyToMany(() => Article, "writers")
declare public static articles: () => Promise<Article[]>;
}@Entity("articles")
export class Article extends DenoDB.Model {
declare public static writers: () => Promise<User[]>;
}