我试图在中间的表中将两个模型与M:N(User.ts和List.ts)相关联。在本例中,我使用typescript-sequelize包来创建模型,在包的文档中,我可以像在sequelize中那样在表中使用.create方法。
我在List上创建了这个方法,并给予了两个参数,第一个参数是要添加到表中的所有信息,第二个参数应该是与另一个列表的关联,但我阅读了该方法的文档,没有找到它的语法。
- https://sequelize.org/docs/v6/advanced-association-concepts/creating-with-associations/*https://www.npmjs.com/package/sequelize-typescript#multiple-relations-of-same-models
这是路由列表。ts:
import express from "express";
import { List } from "../models/List";
import { User } from "../models/User";
router.post("/", async (req, res) => {
const { title, list, tags } = req.body;
const lists = await List.findAll();
if (!title || !list || !tags) {
return res.status(400).json("Missing values");
} else {
req.body.id = lists.length + 1;
await List.create(req.body, { include: [User] });
return res.status(201).json("The list was succesfully created");
}
});
这是List.ts(型号)
import {
Table,
Column,
Model,
PrimaryKey,
BelongsToMany,
DataType,
} from "sequelize-typescript";
import { User } from "./User";
import { UserList } from "./UserList";
@Table
export class List extends Model<List> {
@PrimaryKey
@Column
id!: number;
@Column
title!: string;
list!: {
enumList: string[];
};
tags!: {
enumTags: string[];
};
@Column({
type: DataType.ARRAY(DataType.JSON),
defaultValue: [],
})
comments!: {
idUserComent: number;
userComent: string;
}[];
@BelongsToMany(() => User, () => UserList)
users!: User[];
}
这是用户.ts(型号)
import {
Table,
Column,
Model,
PrimaryKey,
Default,
Unique,
HasMany,
BelongsToMany,
HasOne,
} from "sequelize-typescript";
import { Note } from "./Note";
import { UserList } from "./UserList";
import { Role } from "../types";
import Calendar from "./Calendar";
@Table
export class User extends Model<User> {
@PrimaryKey
@Column
id!: number;
@Column
nickname!: string;
@Unique
@Column
email!: string;
@Default(false)
@Column
verifiedEmail!: boolean;
@Column
password!: string;
@Column
role!: Role;
@Column
avatar!: string;
@HasMany(() => Note)
notes!: Note[];
@HasOne(() => Calendar)
calendar!: Calendar;
@BelongsToMany(() => User, () => UserList)
users!: User[];
}
我的问题是,我如何告诉sequelize用一个特定用户的id创建中间表?我必须手动地在中间表UserList.ts上用另一个.create来做吗?
我尝试在所有地方添加用户的id,结果要么是语法错误,要么是表工作正常,但中间表不工作。
Github回购:https://github.com/Koppeks/Api-ts
1条答案
按热度按时间kcugc4gi1#
我认为您必须创建一个新的模型UserList,以便在模型User和模型List之间进行关联