Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何使用TypeForm中的queryBuilder优化查询以选择内容?_Typescript_Typeorm - Fatal编程技术网

Typescript 如何使用TypeForm中的queryBuilder优化查询以选择内容?

Typescript 如何使用TypeForm中的queryBuilder优化查询以选择内容?,typescript,typeorm,Typescript,Typeorm,我有3个实体:用户、点和东西。 一个用户可以有很多点,一个点可以有很多东西 目前我正在编写两个查询,一个用于验证用户上是否存在spot,另一个用于从spot获取内容。(参见index.js) 如何使用createQueryBuilder(不使用repo.find)编写一个查询,根据user.id和spot.id选择所有内容?我知道这其中涉及到一些参与,但我不能对此置之不理 这是守则的相关部分: const spot=wait spotRepo.createQueryBuilder('spot')

我有3个实体:用户、点和东西。 一个用户可以有很多点,一个点可以有很多东西

目前我正在编写两个查询,一个用于验证用户上是否存在spot,另一个用于从spot获取内容。(参见
index.js

如何使用
createQueryBuilder
(不使用
repo.find
)编写一个查询,根据
user.id
spot.id
选择所有内容?我知道这其中涉及到一些参与,但我不能对此置之不理

这是守则的相关部分:

const spot=wait spotRepo.createQueryBuilder('spot'))
.innerJoin('spot.user','user'))
.where('user.id=:id',{id:1})
.andWhere('spot.id=:id',{id:1})
.getOne();
如果(点!==未定义){
控制台日志(spot);
console.log('gotthespot');
const spotWithThings=wait spotRepo.createQueryBuilder('spot'))
.leftJoinAndSelect('spot.things','things')
.where('spot.id=:id',{id:spot.id})
.getOne();
console.log(spotWithThings);
}

运行此项目的步骤:

  • git克隆https://github.com/fabianmoronzirfas/typeorm-how-to-write-smarter-queries-questionmark.git /测试回购和cd测试回购
  • 运行
    npmi
    命令
  • ormconfig.json
    文件中设置数据库设置
  • 启动数据库
    docker组合
  • 运行
    npm start
    命令
  • 这是
    index.ts

    导入“反映元数据”;
    从“typeorm”导入{createConnection,getRepository};
    从“/entity/User”导入{User};
    从“./entity/Spot”导入{Spot};
    从“./entity/Thing”导入{Thing};
    createConnection()。然后(异步连接=>{
    {
    log(“将新数据插入数据库…”);
    const user=新用户();
    常数点=新点();
    //常量事物=[];
    for(设i=0;i<5;i++){
    const thing=新事物();
    if(spot.things==未定义){
    spot.things=[thing];
    }否则{
    点、物、推(物);
    }
    等待连接。经理。保存(东西);;
    }
    user.spots=[spot];
    等待连接。管理器。保存(用户);
    等待连接。管理器。保存(现场);
    console.log('setup done');
    }
    const spotRepo=getRepository(Spot);
    const spot=wait spotRepo.createQueryBuilder('spot')
    .innerJoin('spot.user','user'))
    .where('user.id=:id',{id:1})
    .andWhere('spot.id=:id',{id:1})
    .getOne();
    如果(点!==未定义){
    控制台日志(spot);
    console.log('gotthespot');
    const spotWithThings=wait spotRepo.createQueryBuilder('spot'))
    .leftJoinAndSelect('spot.things','things')
    .where('spot.id=:id',{id:spot.id})
    .getOne();
    console.log(spotWithThings);
    }否则{
    log(`No spot',用户id${1}`);
    }
    }).catch(错误=>console.log(错误));
    
    这是
    Spot.ts

    从“typeorm”导入{Entity,PrimaryGeneratedColumn,Column,manytone,OneToMany};
    从“/User”导入{User};
    从“./Thing”导入{Thing};
    @实体()
    出口级现货{
    @PrimaryGeneratedColumn()
    id:编号;
    @多通(_type=>User,User=>User.spots)
    公共用户:用户;
    @OneToMany(_type=>Thing,(Thing)=>Thing.spot{
    是的,
    })
    公共事物!:事物[];
    }
    
    这是一件好事

    从“typeorm”导入{Entity,PrimaryGeneratedColumn,manytone,JoinColumn};
    从“/Spot”导入{Spot};
    @实体()
    出口类物品{
    @PrimaryGeneratedColumn()
    id:编号;
    @很多事(_type=>Spot,Spot=>Spot.things{
    答:是的,
    //是的,
    })
    @JoinColumn()
    公共场所!:场所;
    }
    
    这是
    User.ts

    import{Entity,PrimaryGeneratedColumn,OneToMany}来自“typeorm”;
    从“/Spot”导入{Spot};
    @实体()
    导出类用户{
    @PrimaryGeneratedColumn()
    id:编号;
    @OneToMany(_type=>Spot,Spot=>Spot.user{
    答:是的,
    })
    公共场所:Spot[];;
    }
    
    这是ormconfig.json

    {
       "type": "postgres",
       "host": "127.0.0.1",
       "port": 5432,
       "username": "postgres",
       "password": "postgres_password",
       "database": "postgres",
       "synchronize": true,
       "dropSchema": true,
       "logging": false,
       "entities": [
          "src/entity/**/*.ts"
       ],
       "migrations": [
          "src/migration/**/*.ts"
       ],
       "subscribers": [
          "src/subscriber/**/*.ts"
       ],
       "cli": {
          "entitiesDir": "src/entity",
          "migrationsDir": "src/migration",
          "subscribersDir": "src/subscriber"
       }
    }
    
    {
       "compilerOptions": {
          "lib": [
             "es5",
             "es6",
             "dom"
    
          ],
          "target": "es5",
          "module": "commonjs",
          "moduleResolution": "node",
          "outDir": "./build",
          "emitDecoratorMetadata": true,
          "experimentalDecorators": true,
          "sourceMap": true
       }
    }
    
    这是我的docker-compose.yml

    version: '3'
    services:
      postgres:
        container_name: 'pgdb'
        image: 'mdillon/postgis:10'
        ports:
          - '5432:5432'
    
    这是package.json

    {
       "name": "typeorm-smarter-req",
       "version": "1.0.0",
       "description": "",
       "main": "index.js",
       "scripts": {
          "test": "echo \"Error: no test specified\" && exit 1",
          "start": "ts-node src/index.ts"
       },
       "author": "",
       "license": "ISC",
       "dependencies": {
          "pg": "^7.11.0",
          "reflect-metadata": "^0.1.10",
          "typeorm": "0.2.18"
       },
       "devDependencies": {
          "ts-node": "3.3.0",
          "@types/node": "^8.0.29",
          "typescript": "3.3.3333"
       }
    }
    
    
    这是tsconfig.json

    {
       "type": "postgres",
       "host": "127.0.0.1",
       "port": 5432,
       "username": "postgres",
       "password": "postgres_password",
       "database": "postgres",
       "synchronize": true,
       "dropSchema": true,
       "logging": false,
       "entities": [
          "src/entity/**/*.ts"
       ],
       "migrations": [
          "src/migration/**/*.ts"
       ],
       "subscribers": [
          "src/subscriber/**/*.ts"
       ],
       "cli": {
          "entitiesDir": "src/entity",
          "migrationsDir": "src/migration",
          "subscribersDir": "src/subscriber"
       }
    }
    
    {
       "compilerOptions": {
          "lib": [
             "es5",
             "es6",
             "dom"
    
          ],
          "target": "es5",
          "module": "commonjs",
          "moduleResolution": "node",
          "outDir": "./build",
          "emitDecoratorMetadata": true,
          "experimentalDecorators": true,
          "sourceMap": true
       }
    }
    

    您想要获取内容,因此从内容repo开始,并询问问题以获取多个内容,根据连接定义的约束进行过滤:

    const thingRepo = entityManager.getRepository(Thing);
    const things = thingRepo.createQueryBuilder('thing')
        .leftJoinAndSelect('thing.spot', 'spotThing')
        .leftJoinAndSelect('spotThing.user', 'userSpot')
        .where('spotThing.id = :spotId', {spotId})
        .andWhere('userSpot.id = :userId', {userId})
        .getMany();
    

    作品就像一个符咒。非常感谢。