我有一个Book
表,一个Category
表和一个名为BookCategories
的连接表。这是一个过于简化的结构:
books {
id,
name,
hash // unique
}
categories {
id,
name
}
book_categories {
id,
book_hash,
category_id
}
由于应用的工作方式,决定使用联接表中的book_hash
而不是book_id
。
以下是3个表之间的 Sequelize 关系:
// book
Book.hasMany(models.bookCategories, { foreignKey: 'book_hash' });
// category
Category.hasMany(models.bookCategories, { foreignKey: 'category_id' });
// bookCategories
BookCategories.belongsTo(models.book, { foreignKey: 'collection_hash' });
BookCategories.belongsTo(models.category, { foreignKey: 'category_id' });
我正在使用Sequelize和GraphQL,因此在books
上创建CategoryType
字段时,一切都很有效:
books: {
type: new GraphQLList(BookType),
args: defaultListArgs(),
async resolve(f, args) {
return await f.getBookCategories(args);
// normally doesn't return, uses results to get book hashes and return books
}
}
它运行以下查询:
SELECT `id`, `name` FROM `categories` ASC;
SELECT `id`, `book_hash`, `category_id` FROM `book_categories` AS `bookCategories` WHERE `bookCategories`.`category_id` IN (1, 2, 3, 4, 5);
但是当反过来这样做时,通过BookType
请求bookCategories,它不会:
categories: {
type: new GraphQLList(CategoryType),
args: defaultListArgs(),
async resolve(f, args) {
return await f.getBookCategories(args);
// normally doesn't return, uses results to get category ids and return categories
}
}
它运行这些查询:
SELECT `id`, `name`, `hash`, FROM `books` AS `book` WHERE `book`.`hash` = 'ft3qvqlj';
SELECT `id`, `book_hash`, `category_id` FROM `book_categories` AS `bookCategories` WHERE `bookCategories`.`book_hash` IN (93586);
正如您所看到的,即使我将外键设置为两个关系的哈希值,它仍然使用book id来进行查询。是否与hash
表中books
不是主键的事实有关?
有没有办法解决这个问题,还是我必须重做数据库结构?