gpt4 book ai didi

arrays - 为什么我的多对多关系字段未定义?

转载 作者:行者123 更新时间:2023-12-05 00:46:52 34 4
gpt4 key购买 nike

我正在尝试创建一个关注者/关注系统,当我尝试将新用户附加到以下列表时,我收到错误 Cannot read property 'push' of undefined。这最终创建了 2 个单独的表,一个用于关注其他用户的用户,一个用于被其他用户关注的用户。不知道为什么它不拿起领域?任何帮助表示赞赏。

import { Length } from "class-validator";
import {
Column,
CreateDateColumn,
Entity,
JoinTable,
ManyToMany,
OneToMany,
PrimaryColumn,
RelationCount,
Unique,
UpdateDateColumn
} from "typeorm";

export class User {

@PrimaryColumn()
public user_id: string;

@Column()
public first_name: string;

@Column()
public last_name: string;

@Column()
public email: string;

@Column()
public phone_number: string;

@Column()
public username: string;

@Column()
@CreateDateColumn()
public created_on: Date;

@Column()
@UpdateDateColumn()
public updated_at: Date;

@ManyToMany((type) => User, (user) => user.following)
@JoinTable()
public followers: User[];

@ManyToMany((type) => User, (user) => user.followers)
@JoinTable()
public following: User[];

@RelationCount((user: User) => user.followers)
public followers_count: number;

@RelationCount((user: User) => user.following)
public following_count: number;
}

const { user_id, 
follow_user_id } = req.
const user_repo = getRepository(User);
const user = await user_repo.findOne({
where: {user_id}
});
const follow_user = new User();

follow_user.user_id = follow_user_id;
user.following.push(follow_user);
const result = user_repo.save(user);

错误指的是这一行 user.following.push(follow_user);

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of undefined

最佳答案

我在 OneToMany 和 ManyToOne 关系中遇到了类似的错误,其中相对返回 null/undefined。

我正在使用的解决方法是将它放在 User 类中:

  @AfterLoad()
async nullChecks() {
if (!this.followers) {
this.followers = []
}

if (!this.following) {
this.following = []
}
}

documentation

关于arrays - 为什么我的多对多关系字段未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59351687/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com