从外键搜索 table - mysql
Search from keys in foreign table - mysql
我正在使用 nestjs 和 typeorm (Mysql)。我有两个 tables 用户和类别,在类别 table 中我有一个链接到用户 ID 的外键。我想要做的是在查询类别 table.
时从用户 table 搜索 firstName
我有 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 吗?
感谢您的帮助!
您需要先加入 category
和 user
。尝试这样的事情:
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}%` });
}
我正在使用 nestjs 和 typeorm (Mysql)。我有两个 tables 用户和类别,在类别 table 中我有一个链接到用户 ID 的外键。我想要做的是在查询类别 table.
时从用户 table 搜索 firstName我有 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 吗? 感谢您的帮助!
您需要先加入 category
和 user
。尝试这样的事情:
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}%` });
}