首页 > 解决方案 > 在当前范围内没有为 struct `schema::todos::table` 找到名为 `table` 的函数或关联项

问题描述

我想创建一个函数,使用 Diesel 读取 postgresql 中的所有数据并将其作为Vec.

错误信息

我相信这个错误信息表明todos没有实现该table功能。我认为这不是问题,因为我#[derive(Queryable)]在模型中有。

error[E0599]: no function or associated item named `table` found for struct `schema::todos::table` in the current scope
 --> src/actions.rs:9:42
  |
9 |       let entries: Vec<TodoEntry> = todos::table.load::<TodoEntry>(&connection).expect("Error loading todos");
  |                                            ^^^^^ function or associated item not found in `schema::todos::table`
  | 
 ::: src/schema.rs:1:1
  |
1 | / table! {
2 | |     todos (id) {
3 | |         id -> Int4,
4 | |         body -> Text,
5 | |     }
6 | | }
  | |_- function or associated item `table` not found for this
  |
  = help: items from traits can only be used if the trait is in scope
  = note: the following trait is implemented but not in scope; perhaps add a `use` for it:
          `use crate::diesel::associations::HasTable;`

相关代码

货运.toml

[package]
authors = ["hogehogehoge"]
edition = "2018"
name = "todo"
version = "0.1.0"
[dependencies]
actix-web = "3"
askama = "*"
thiserror = "*"
diesel = { version = "1.4.4", features = ["postgres", "r2d2"] }
r2d2 = "0.8"
dotenv = "0.15.0"

柴油机.toml

[print_schema]
file = "src/schema.rs"

动作.rs

该文件有一个函数,可以将数据库中注册的数据返回为Vec.

use diesel::pg::PgConnection;

use crate::models;
use crate::templates::TodoEntry;

pub fn return_all(connection: &PgConnection) -> Result<Vec<TodoEntry>, diesel::result::Error> {
    use crate::schema::todos::dsl::*;

    let entries: Vec<TodoEntry> = todos::table.load::<TodoEntry>(&connection).expect("Error loading todos");
    Ok(entries)
}

模板.rs

该文件确定要在数据库中注册的数据类型,然后添加

#[derive(Queryable)]
pub struct Todo {
    pub id: u32,
    pub text: String,
}

架构.rs

table! {
    todos (id) {
        id -> Int4,
        body -> Text,
    }
}

标签: postgresqlrustrust-diesel

解决方案


我认为您混合了两种不同的方式来引用特定表。根据相应的指南,它是crate::schema::table_name::tablecrate::schema::table_name::dsl::table_name。你尝试使用crate::schema::table_name::dsl::table_name::table.


推荐阅读