mysql - 自引用多对多关系类型ORM

标签 mysql node.js orm typeorm

我刚开始使用 TypeORM,我正在努力让以下关系发挥作用:

User->Friends,而 Friend 也是一个用户对象。 但是,我的 setter/getter getFriends 和 getFriendsInverse 正在工作;我现在确实想区分两者。换句话说;当我执行 mysql 连接时,我不想对 friends 进行左连接而对 inverseFriends 进行另一个连接。

getter getFriends() 需要返回所有 friend ,无论我在对象的哪“边”。

这有意义吗?

这是我的模型定义:

getFriends() {
    // This method should also return inverseFriends;
    // I do not want to return the concat version; this should
    // happen on the database/orm level
    // So I dont want: this.friends.concat(this.inverseFriends) 
    return this.friends;
}

@ManyToMany(type => User, user => user.friendsInverse, {
    cascadeInsert: false,
    cascadeUpdate: false,
})
@JoinTable()
friends = [];

@ManyToMany(type => User, user => user.friends, {
    cascadeInsert: true,
    cascadeUpdate: true,
    cascadeRemove: false,
})
friendsInverse = [];

我希望有人能理解我的问题 :D 谢谢 马特

最佳答案

您可以 self 引用您的关系。这是一个简单的有向图示例(也就是一个 Node 可以有一个父 Node 和多个子 Node )。

@Entity()
export class Service extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;
  
  @Column()
  @Index({ unique: true })
  title: string;

  @ManyToOne(type => Service, service => service.children)
  parent: Service;

  @OneToMany(type => Service, service => service.parent)
  children: Service[];
}

需要牢记的重要一点是,当使用 find* 函数从数据库中读取对象时,这些关系不会自动加载。

要实际加载它们,您现在必须使用查询生成器并加入它们。 (您可以加入多个级别。)示例:

let allServices = await this.repository.createQueryBuilder('category')
  .andWhere('category.price IS NULL')
  .innerJoinAndSelect('category.children', 'product')
  .leftJoinAndSelect('product.children', 'addon')
  .getMany();

请注意我是如何使用不同的名称来引用它们的(categoryproductaddon)。

关于mysql - 自引用多对多关系类型ORM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43747765/

相关文章:

MySQL 5.5 'Binary log is not open',错误代码 : 1236

php - 如何从iphone post请求中获取json数据

python - 如何让python不将L附加到longs或在django模板中忽略

java - 仅具有 CascadeType.REMOVE 的双向 @OneToOne 保存更改 : that is not wanted

mysql - 为什么唯一键的列名在括号中重复?

node.js - 将变量发送到布局

node.js - NodeMailer 附件不使用 smtp/gmail 发送

node.js - 如何使用 Jade 迭代数组创建 html 表

java - 如何从 JDBC 查询中获取所有元素

java - Hibernate : many to many linker table, 最佳 OO 设计