rust - 在 Diesel 中引用同一个表的多个外键
问题描述
我正在尝试创建一个引用同一个表两次的结构。这样做的目的是创建一种类别的层次结构。这是我要为以下表格做的事情:
create table product_category_rollup(
id serial primary key,
upper_category_id integer not null,
lower_category_id integer not null,
foreign key (upper_category_id) references product_category(id),
foreign key (lower_category_id) references product_category(id)
);
create table product_category(
id serial primary key,
name varchar unique not null
);
我正在尝试创建匹配的结构,如下所示:
#[derive(Identifiable, Queryable)]
#[table_name = "product_category"]
pub struct ProductCategory {
id: i32,
name: String,
}
#[derive(Queryable, Identifiable, Associations)]
#[belongs_to(ProductCategory, foreign_key="upper_category_id")]
#[belongs_to(ProductCategory, foreign_key="lower_category_id")]
#[table_name = "product_category_rollup"]
pub struct ProductCategoryRollup {
id: i32,
upper_category_id: i32,
lower_category_id: i32,
}
我收到一条错误消息:
error[E0119]: conflicting implementations of trait `diesel::associations::BelongsTo<entities::ProductCategory>` for type `entities::ProductCategoryRollup`:
--> src/entities.rs:29:35
|
29 | #[derive(Queryable, Identifiable, Associations)]
| ^^^^^^^^^^^^
| |
| first implementation here
| conflicting implementation for `entities::ProductCategoryRollup`
|
= note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)
让多个外键引用同一个表的正确方法是什么?这是柴油机中尚未解决的一些固有限制吗?
解决方案
BelongsTo
特征定义为:
pub trait BelongsTo<Parent> {
type ForeignKey: Hash + Eq;
type ForeignKeyColumn: Column;
fn foreign_key(&self) -> Option<&Self::ForeignKey>;
fn foreign_key_column() -> Self::ForeignKeyColumn;
}
由于ForeignKey
(and ForeignKeyColumn
) 是关联类型,而不是泛型参数,一个给定的Child
只能有一个BelongsTo<Parent>
.
总的来说,这似乎BelongsTo
是相当有限的。请注意,它也仅限于单列。
推荐阅读
- android - 如何在Android中为带有底部导航栏的片段提供向后滑动动画
- python - 无法在 Python 中为循环中的 PIPE 使用分配内存错误?
- angular-material - Angular-material:为主题中的按钮添加边框
- python - 为什么不正确地解释这个 ISO 日期时间字符串?
- forms - Drupal 9 - 使用控制器的自定义模块中的表单 - html标签表单不存在
- c++ - 如果我使用 AVX2 创建应用程序,它会在其他机器上运行吗?
- laravel - Laravel 导出可下载的 CSV 文件
- python - 对 Python 编程有点陌生,正在尝试一个问题。我只是不知道为什么这个错误不断弹出。对我来说真的没有意义
- java - 登录 Vaadin8 后如何更改 JSESSIONID?
- c# - ClientWebSocket - SocketException:无法建立连接