gpt4 book ai didi

join - Diesel 连接无法推断类型

转载 作者:行者123 更新时间:2023-11-29 08:31:07 54 4
gpt4 key购买 nike

rust 版本 1.18.3柴油版本 1.0.0Postgres 11在 debian 10 上

我正在尝试使用 Diesel ORM 和 postgres 在 Rust 中连接两个表。该表是帖子和用户,我想将用户的用户名加入到帖子表中。

我在 CREATE TABLE 语句中的帖子中实现了一个外键,指向用户中的 id,因此 diesel 会自动派生可连接对象!和 allow_tables_to_appear_in_same_query! schema.rs 中的宏。然而,当我尝试在我的代码中加入表时,rust 无法推断类型,我也不知道如何注释类型。

这是我的main.rs

extern crate cmsbackend;
extern crate diesel;

use self::cmsbackend::*;
use self::models::*;
use self::diesel::prelude::*;

fn main() {
use cmsbackend::schema::*;

let connection = establish_connection();

let results = users::table.inner_join(posts::table)
.select((users::name, posts::title))
.load(&connection);
}

我收到此错误消息:

error[E0282]: type annotations needed for `std::result::Result<std::vec::Vec<U>, diesel::result::Error>`
--> src/bin/main.rs:20:10
|
18 | let results = users::table.inner_join(posts::table)
| ------- consider giving `results` the explicit type `std::result::Result<std::vec::Vec<U>, diesel::result::Error>`, where the type parameter `U` is specified
19 | .select((users::name, posts::title))
20 | .load(&connection);
| ^^^^ cannot infer type for `U`

有关此错误的更多信息,请尝试 rustc --explain E0282。错误:无法编译 cmsbackend

我是否可能需要在我的结构定义中派生其他东西:

use diesel::pg::data_types::*;

#[derive(Queryable)]
pub struct Post {
pub id: i32,
pub title: String,
pub body: Option<String>,
pub published: bool,
pub user_id: i32,
pub creation_date: PgTimestamp,
pub last_edit: PgTimestamp,
pub foto: Option<String>,
}

#[derive(Queryable)]
pub struct User {
pub id: i32,
pub name: String,
pub pw: String,
}

我如何编译它?


编辑:
感谢您的意见。这是我的 schema.rs 的内容

table! {
posts (id) {
id -> Int4,
title -> Varchar,
body -> Nullable<Text>,
published -> Bool,
user_id -> Int4,
creation_date -> Timestamp,
last_edit -> Timestamp,
foto -> Nullable<Varchar>,
}
}

table! {
users (id) {
id -> Int4,
name -> Varchar,
pw -> Varchar,
}
}

joinable!(posts -> users (user_id));

allow_tables_to_appear_in_same_query!(
posts,
users,
);

最佳答案

我已经解决了这个问题。由于结构中的可查询派生无法推断连接产生的数据类型,因此您必须像这样注释结构字段的数据类型:

let data: Vec<(String, String)> = users::table.inner_join(notes::table)
.select((users::name, notes::title))
.load(&connection)
.expect("error");

在我尝试之前

let data: Vec<(User, Post)> = posts::table.inner_join(users::table)
.select((users::name, notes::title))
.load(&connection)
.expect("error");

编译器在加载时抛出一个错误,指出 Trait Queryable 没有实现。

另请参阅文档:https://github.com/diesel-rs/diesel/blob/master/guide_drafts/trait_derives.md

关于join - Diesel 连接无法推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57604805/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com