【问题标题】:Search from keys in foreign table - mysql从外部表中的键搜索 - mysql
【发布时间】:2021-10-31 22:21:47
【问题描述】:

我正在使用 nestjs 和 typeorm (Mysql)。我有两个表用户和类别,在类别表中我有一个链接到用户 ID 的外键。我想要做的是在查询类别表时从用户表中搜索名字。

我有 2 个搜索字段类别名称和用户名。为了搜索类别名称,我所做的是

const query = this.createQueryBuilder('category');
if (categoryName) {
      query.andWhere('category.categoryName LIKE :categoryName', {
        categoryName: `%${categoryName}%`,
      });
    }

用于搜索用户名

if (userName) {
      query.andWhere('category.user.firstName LIKE :userName', {
        userName: `%${userName}%`,
      });
    }

但是上面那个给了我错误。知道如何使用 typeorm 和 nestjs 吗? 感谢您的帮助!

【问题讨论】:

    标签: mysql node.js nestjs typeorm


    【解决方案1】:

    您需要先加入categoryuser。试试这样的:

    const query = this.createQueryBuilder('category');
    
    if (categoryName) {
      query.andWhere('category.categoryName LIKE :categoryName', { categoryName: `%${categoryName}%` });
    }
    
    if (userName) {
      query
        .leftJoinAndSelect('category.user', 'user')
        .andWhere('user.firstName LIKE :userName', { userName: `%${userName}%` });
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 2012-03-26
      • 2014-03-05
      • 1970-01-01
      • 2013-11-23
      • 2017-03-30
      • 1970-01-01
      相关资源
      最近更新 更多