denodb: Uncaught ReferenceError: Cannot access 'Model' before initialization
Hello, I encountered this error when trying to achieve one-to-many relationship
error: Uncaught ReferenceError: Cannot access 'UserModel' before initialization userId: Relationships.belongsTo(UserModel),
I have 2 models Article
import {
DataTypes,
Model,
Relationships,
} from "https://deno.land/x/denodb/mod.ts";
import { UserModel } from "./user.ts";
export class ArticleModel extends Model {
static table = "articles";
static timestamps = true;
static fields = {
id: { primaryKey: true, autoIncrement: true },
content: DataTypes.TEXT,
title: DataTypes.STRING,
tags: DataTypes.ENUM,
likeCount: DataTypes.INTEGER,
userId: Relationships.belongsTo(UserModel),
};
static user() {
return this.hasOne(UserModel);
}
}
User
import { ArticleModel } from "./article.ts";
export class UserModel extends Model {
static table = "users";
static timestamps = true;
static fields = {
id: { primaryKey: true, autoIncrement: true },
username: DataTypes.STRING,
password: DataTypes.STRING,
};
static articles() {
return this.hasMany(ArticleModel);
}
}
Seems like a cyclic dependency problem here because User class references Article class and vice versa. Please help
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 16 (5 by maintainers)
Hey guys,
I think the way this could be done without cyclic dependencies is by taking the relationships outside of the model definition.
At the moment, if you make a one-to-one relationship (or many-to-many, etc.), it has to be done this way:
I could change the
belongsToAPI so you could have:Also, thank you so much for your patience. I only got back to help recently, didn’t have the time before.
Anyways, let me know what you think or feel free to suggest another syntax 😃
This is what I’m looking for !
@eveningkid, I was checking this issue (I’m in this situation right now)… How about let pass the table name directly to the belongsTo parameter. Something like:
So we avoid falling in the typescript error @hoangph271 said. Solutions for desperate moments
I think this is more of a coding problem than a denodb problem…!
You can avoid cyclic dependency by just declaring all models in a single file…?