视图实体
什么是视图实体?
视图实体是一个映射到数据库视图的类。
你可以通过定义一个 新类来创建一个视图实体,并用@ViewEntity()
来标记:
@ViewEntity()
接收以下参数:
name
- 视图名称。 如果未指定,则从实体类名生成视图名称。database
- 所选DB服务器中的数据库名称。schema
- 架构名称。expression
- 视图定义。 必需参数。
expression
可以是带有正确转义的列和表的字符串,取决于所使用的数据库(示例中为postgres):
@ViewEntity({
expression: `
SELECT "post"."id" "id", "post"."name" AS "name", "category"."name" AS "categoryName"
FROM "post" "post"
LEFT JOIN "category" "category" ON "post"."categoryId" = "category"."id"
`
})
或者是QueryBuilder的一个实例
@ViewEntity({
expression: (connection: Connection) => connection.createQueryBuilder()
.select("post.id", "id")
.addSelect("post.name", "name")
.addSelect("category.name", "categoryName")
.from(Post, "post")
.leftJoin(Category, "category", "category.id = post.categoryId")
})
注意: 由于驱动程序的限制,不支持参数绑定。请改用文字参数。
@ViewEntity({
expression: (connection: Connection) => connection.createQueryBuilder()
.select("post.id", "id")
.addSelect("post.name", "name")
.addSelect("category.name", "categoryName")
.from(Post, "post")
.leftJoin(Category, "category", "category.id = post.categoryId")
.where("category.name = :name", { name: "Cars" }) // <-- 这是错的
.where("category.name = 'Cars'") // <-- 这是对的
})
每个视图实体都必须在连接选项中注册:
import {createConnection, Connection} from "typeorm";
import {UserView} from "./entity/UserView";
const connection: Connection = await createConnection({
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
entities: [UserView]
});
或者你可以指定包含所有实体的整个目录 - 所有实体都将被加载:
import {createConnection, Connection} from "typeorm";
const connection: Connection = await createConnection({
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
entities: ["entity/*.js"]
});