嗨,我有一个问题,拿我的资料,我的个人资料,孩子和玩具,这份档案是孩子的父母和孩子是玩具的父母。我已经创建了用“一对多”和“多对一”的配置文件和孩子来获取数据。现在我要把玩具放在孩子的属性里。
这是我的桌子看起来像..。

这是我的实体。
ProfileEntity.js
var {EntitySchema} = require("typeorm")
module.exports = new EntitySchema({
name "Profile",
tableName: "profile",
columns: {
profile_id: {
primary: true,
type: "integer"
},
name: {
type: "varchar"
},
age: {
type: "integer"
}
},
relations: {
kids: {
target: "Kids",
type: "one-to-many",
inverseSide: "profile"
}
}
});KidsEntity.js
var {EntitySchema} = require("typeorm")
module.exports = new EntitySchema({
name "Kids",
tableName: "kid",
columns: {
kid_id: {
primary: true,
type: "integer",
},
profile_id: {
primary: true,
type: "integer"
},
kid_name: {
type: "varchar"
},
age: {
type: "integer"
}
},
relations: {
profile: {
target: "Profile",
type: "many-to-one",
joinColumn: {
name: "profile_id"
}
}
}
});现在当我打电话给
const data = await connection.getRepository("Profile").find({
where: {
name: "Doe"
},
relations: {
kids: true
}
});它给了我这样一个数组,它是正确的。
[
{
"profile_id": 1,
"name": "Doe",
"age": 28,
"kids": [
{
"kid_id": 1,
"profile_id": 1,
"kid_name": "Coco",
"age": 2
},
{
"kid_id": 2,
"profile_id": 1,
"kid_name": "Melon",
"age": 3
}
]
}
]现在,我希望玩具数据位于子类属性中,如下所示。
[
{
"profile_id": 1,
"name": "Doe",
"age": 28,
"kids": [
{
"kid_id": 1,
"profile_id": 1,
"kid_name": "Coco",
"age": 2
"toys": [
{
"toy_id": 1,
"kid_id": 1,
"toy_name": "Golf Set",
"for": "2-3"
},
{
"toy_id": 2,
"kid_id": 1,
"toy_name": "Trucks",
"for": "2-3"
},
]
},
{
"kid_id": 2,
"profile_id": 1,
"kid_name": "Melon",
"age": 3,
"toys": [
{
"toy_id": 3,
"kid_id": 2,
"toy_name": "Barbie",
"for": "3-5"
}
]
}
]
}
]我如何获取这样的数据?提前谢谢。
发布于 2022-10-09 12:11:16
根据您的数据结构,这似乎是嵌套关系,而不是“多对多”关系。如果你真的想要多对多,那么你就可以定义一个单独的“玩具”表,然后像"kids_toys“表那样在”孩子“和”玩具“之间建立联系。
但是现在,按照您当前的设置。首先,你可以定义“玩具”的关系,就像你对“孩子”所做的那样:
module.exports = new EntitySchema({
name "Kids",
...
relations: {
profile: {
...
},
toys: {
target: "Toys",
type: "one-to-many",
inverseSide: "kid"
}
}然后为Toys表本身添加定义(适当地将其他字段添加到Toys.js):
module.exports = new EntitySchema({
name "Toys",
columns: {
toy_id: {
primary: true,
type: "integer",
},
kid_id: {
type: "integer"
},
...
}
...
relations: {
kid: {
target: "Kids",
type: "many-to-one",
joinColumn: {
name: "kid_id"
}
}
}最后,执行嵌套查询:
const data = await manager.getRepository("Profile").find({
where: {
name: "Doe"
},
relations: {
kids: {
toys: true
}
}
});请注意,打字机的目标主要是打字本,在打字本中使用打字本要容易得多(更不用说写了)。不确定,为什么要使用带有typeorm的纯文本javascript来定义实体?
https://stackoverflow.com/questions/73983912
复制相似问题