How to use typeorm

Comprehensive typeorm code examples:

How to use typeorm.Equal:

166
167
168
169
170
171
172
173
174
175
 * @throws {Error}
 */
async fetchById(id, repoName) {
    try {
        const repo = this.#dataSource.getRepository(repoName);
        let res = await repo.findBy({ id: orm.Equal(id) });
        if (res.length > 0) {
            res = res[0];
        } else {
            res = null;

How to use typeorm.In:

214
215
216
217
218
219
220
221
222
223
    driversIds = post.driversId.split(',').map(function (to) { return +to; });
    car = new car_entity_1.CarEntity();
    return [4 /*yield*/, manufacturer_entity_1.ManufacturerEntity.findOne({ where: { id: +post.manufacturerId } })];
case 1:
    manufacturer = _a.sent();
    return [4 /*yield*/, driver_entity_1.DriverEntity.find({ where: { id: typeorm_1.In(driversIds) } })];
case 2:
    drivers = _a.sent();
    car.manufacturer = manufacturer;
    car.drivers = drivers;

How to use typeorm.EntityRepository:

58
59
60
61
62
63
64
65
            return true;
        });
    }
};
UserRepository = __decorate([
    typeorm_1.EntityRepository(User_entity_1.User)
], UserRepository);
exports.UserRepository = UserRepository;

How to use typeorm.Instance:

8
9
10
11
12
13
14
15
16
17

/*
unexpected.addType({
  name: 'typeorm.entity',
  identify: function (value) {
    return value && value instanceof typeorm.Instance;
  },
  inspect: function (value, depth, output, inspect) {
    output
      .text(value.Model.name).text('(')

How to use typeorm.Like:

17
18
19
20
21
22
23
24
25
    continue
  }

  if (Object.prototype.hasOwnProperty.call(filters, key)) {
    formattedFilters.push({
      [key]: searchLikeTypes.includes(fields[key].type) ? Like(`%${filters[key]}%`) : filters[key]
    })
  }
}

How to use typeorm.Association:

25
26
27
28
29
30
31
32
33
34
});

unexpected.addType({
  name: 'typeorm.Association',
  identify: function (value) {
    return value && value instanceof typeorm.Association;
  },
  inspect: function (value, depth, output) {
    output
      .text(value.associationType).text(': ')

How to use typeorm.Not:

212
213
214
215
216
217
218
219
220
const loadedContracts = LoadedContracts.Instance;

const previousContracts: Contract[] = await Contract.find({
    projectId: currentContract.projectId,
    networkId: currentContract.networkId,
    versionId: typeorm.Not(currentContract.versionId),
});

logger.debug(`Found ${previousContracts.length} previous Load contracts in DB`);

How to use typeorm.getConnectionManager:

40
41
42
43
44
45
46
47
48
49
                cfg.entities[i] = Util.getAbsPath([item]);
            }
        });
    }
    const {getConnectionManager} = require('typeorm');
    this.connection = getConnectionManager().create(cfg);
}

/**
 * 获取连接

How to use typeorm.Table:

0
1
2
3
4
5
6
7
8
9
const { MigrationInterface, QueryRunner, QueryBuilder, Table } = require('typeorm');

class PostRefactoring1613820162728 {
  async up(queryRunner) {
    await queryRunner.createTable(
      new Table({
        name: 'map',
        columns: [
          {
            name: 'mavCockpitDisable',

How to use typeorm.IsNull:

84
85
86
87
88
89
90
91
92
93
});

it('expecting 2 participants to have bet of 100', async () => {
  const raffle = await AppDataSource.getRepository(Raffle).findOne({
    relations: ['participants'],
    where:     { winner: IsNull(), isClosed: false },
  });
  assert.strictEqual(raffle.participants.length, 2);
  assert.strictEqual(raffle.participants[0].tickets, 100);
  assert.strictEqual(raffle.participants[1].tickets, 100);

How to use typeorm.getManager:

444
445
446
447
448
449
450
451
452
453
      .catch(function (err) {
        options.error(err);
      });
  }
} else if (currencyOperation.add.includes(action)) {
  // typeorm.getManager()
  // .insert(orm['models'][options['tableName']],reqObj['delta'])
  // .then(function(res){
  // 	options.success(res.identifiers)
  // }).catch(function(err){

How to use typeorm.EntitySchema:

How to use typeorm.MoreThanOrEqual:

22
23
24
25
26
27
28
29
30
31
try {
  if (!res.locals.user || !res.locals.user.is_admin) throw new ErrorMessage('您没有权限进行此操作。');

  let allSubmissionsCount = await JudgeState.count();
  let todaySubmissionsCount = await JudgeState.count({
    submit_time: TypeORM.MoreThanOrEqual(syzoj.utils.getCurrentDate(true))
  });
  let problemsCount = await Problem.count();
  let articlesCount = await Article.count();
  let contestsCount = await Contest.count();

How to use typeorm.Raw:

19
20
21
22
23
24
25
26
27
28
},
email: async email => {
  if (/.+\@.+\..+/.test(email)) {
    const { User } = require('@things-factory/auth-base')
    const user = await getRepository(User).findOne({
      where: { email: Raw(alias => `LOWER(${alias}) LIKE '${email.toLowerCase()}'`) }
    })
    return user ? true : chalk.redBright(`There's no user has ${chalk.cyan(email)} as email.`)
  } else {
    return chalk.redBright('Please type right format of email')

How to use typeorm.getConnection:

18
19
20
21
22
23
24
25
26
  await (new UserSeed().run())
  await (new CredentialSeed().run())

}).then(async () => {

  await getConnection().close()
  console.log('done')

}).catch(async reason => {

How to use typeorm.TableForeignKey:

74
75
76
77
78
79
80
81
82
83
      "default": 'now()'
    }]
  }), true);
case 2:
  _context.next = 4;
  return queryRunner.createForeignKey('product_review', new _typeorm.TableForeignKey({
    columnNames: ['product_id'],
    referencedColumnNames: ['id'],
    referencedTableName: 'product',
    onDelete: 'CASCADE'

How to use typeorm.getRepository:

24
25
26
27
28
29
30
31
32
  await db.cleanup();
  await message.prepare();
});

it('create user1', async () => {
  await getRepository(User).save({
    userName: user1.userName, userId: user1.userId, points: user1.points,
  });
});

How to use typeorm.Brackets:

35
36
37
38
39
40
41
42
43
44
if (currentTeam) {
    users = await User_1.User.createQueryBuilder('user')
        .where('countryId = :countryId', { countryId: user.country.id })
        .andWhere('id != :userId', { userId: user.id })
        .andWhere('id IN (:ids)', { ids: input.invitations.map(i => i.id) })
        .andWhere(new typeorm_1.Brackets(qb => {
        qb.where('teamId IS NULL')
            .orWhere('teamId = :teamId', { teamId: currentTeam.id });
    }))
        .getMany();

How to use typeorm.DataSource:

104
105
106
107
108
109
110
111
112
113
  migrations:    [ `dest/database/migration/sqlite/**/*.js` ],
};

let AppDataSource;
if (process.env.TYPEORM_AppDataSource === 'mysql' || process.env.TYPEORM_AppDataSource === 'mariadb') {
  AppDataSource = new DataSource(MySQLDataSourceOptions);
} else if (process.env.TYPEORM_AppDataSource === 'postgres') {
  AppDataSource = new DataSource(PGDataSourceOptions);
} else {
  AppDataSource = new DataSource(SQLiteDataSourceOptions);

How to use typeorm.createConnection:

376
377
378
379
380
381
382
383
384
385
386
    connectionSettings.username = process.env.TYPEORM_USERNAME;
    connectionSettings.password = process.env.TYPEORM_PASSWORD;
    connectionSettings.database = process.env.TYPEORM_DATABASE;
  }


  typeorm.createConnection(connectionSettings).then((connection) => {
    console.log(logSymbols.success, "Successfully connected to Database!");
    start();
  });
}

How to use typeorm.getCustomRepository:

66
67
68
69
70
71
72
73
74
75
return __awaiter(this, void 0, void 0, function () {
    var tasksRepository, tasks;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                tasksRepository = typeorm_1.getCustomRepository(TasksRespository_1.TasksRepository);
                return [4 /*yield*/, tasksRepository.find({
                        order: {
                            created_at: 'ASC'
                        },