从关系中获取字段而不是对象(typeorm)
get fields instead of object from relation (typeorm)
我是 typeorm 的新手,当我想检索具有关系的 table 时,会在名称为 table 的对象中检索该关系的列。这是一个例子
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm"
import { Photo } from "./Photo"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@OneToMany((type) => Photo, (photo) => photo.user)
photos: Photo[]
}
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm"
import { User } from "./User"
@Entity()
export class Photo {
@PrimaryGeneratedColumn()
id: number
@Column()
url: string
@ManyToOne((type) => User, (user) => user.photos)
user: User
}
const user = await createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.where("user.name = :name", { name: "Timber" })
.getOne()
结果
{
id: 1,
name: "Timber",
photos: [{
id: 1,
url: "me-with-chakram.jpg"
}, {
id: 2,
url: "me-with-trees.jpg"
}]
}
我想获得与 table
的字段处于同一级别的关系字段
预期结果
{
{
id: 1,
name: "Timber",
id: 1,
url: "me-with-chakram.jpg"
}
{
id: 1,
name: "Timber",
id: 2,
url: "me-with-trees.jpg"
}
}
有没有办法做到这一点?我在他们的文档中没有找到任何内容
你可以试试这个,
const user = await createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.select([
'user.id',
'user.name',
'photos.id',
'photos.url'
])
.where("user.name = :name", { name: "Timber" })
.getOne();
我试过使用“*”并且有效
const user = await createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.select('*')
.where("user.name = :name", { name: "Timber" })
.getOne();
我是 typeorm 的新手,当我想检索具有关系的 table 时,会在名称为 table 的对象中检索该关系的列。这是一个例子
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm"
import { Photo } from "./Photo"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@OneToMany((type) => Photo, (photo) => photo.user)
photos: Photo[]
}
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm"
import { User } from "./User"
@Entity()
export class Photo {
@PrimaryGeneratedColumn()
id: number
@Column()
url: string
@ManyToOne((type) => User, (user) => user.photos)
user: User
}
const user = await createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.where("user.name = :name", { name: "Timber" })
.getOne()
结果
{
id: 1,
name: "Timber",
photos: [{
id: 1,
url: "me-with-chakram.jpg"
}, {
id: 2,
url: "me-with-trees.jpg"
}]
}
我想获得与 table
的字段处于同一级别的关系字段预期结果
{
{
id: 1,
name: "Timber",
id: 1,
url: "me-with-chakram.jpg"
}
{
id: 1,
name: "Timber",
id: 2,
url: "me-with-trees.jpg"
}
}
有没有办法做到这一点?我在他们的文档中没有找到任何内容
你可以试试这个,
const user = await createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.select([
'user.id',
'user.name',
'photos.id',
'photos.url'
])
.where("user.name = :name", { name: "Timber" })
.getOne();
我试过使用“*”并且有效
const user = await createQueryBuilder("user")
.leftJoinAndSelect("user.photos", "photo")
.select('*')
.where("user.name = :name", { name: "Timber" })
.getOne();