使用Diesel的`belongs_to`属性时的“使用未声明的类型或模块”

时间:2019-07-02 12:59:12

标签: rust rust-diesel

我松散地遵循Diesel的getting started指南来尝试建立关系数据库,但是在编译时遇到以下错误:

error[E0433]: failed to resolve: use of undeclared type or module `birds`
 --> src/models.rs:9:12
  |
9 | pub struct Bird {
  |            ^^^^ use of undeclared type or module `birds`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0433`.
error: Could not compile `prrr_gql`.

以下是二进制文件:

extern crate prrr_gql;
extern crate diesel;

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

fn main() {
    use prrr_gql::schema::cats::dsl::*;
    use prrr_gql::schema::birds::dsl::*;

    let connection = establish_connection();
    let results = cats.load::<Cat>(&connection)
        .expect("Error hearding cats");

    for cat in results {
        println!("{}", cat.name);
    }
}

和lib.rs(导入为prrr_gql

#[macro_use]
extern crate diesel;
extern crate dotenv;

use diesel::prelude::*;
use diesel::pg::PgConnection;
use dotenv::dotenv;
use std::env;

pub mod schema;
pub mod models;

pub fn establish_connection() -> PgConnection {
    dotenv().ok();

    let database_url = env::var("DATABASE_URL")
        .expect("DATABASE_URL must be set");

    PgConnection::establish(&database_url)
        .expect(&format!("Error connecting to {}", database_url))
}

models.rs

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

#[derive(Queryable, Associations, Debug)]
#[belongs_to(Cat)]
pub struct Bird {
    pub id: i32,
    pub cat_id: i32,
    pub species: String,
    pub colors: String
}

和Diesel生成的schema.rs

table! {
    birds (id) {
        id -> Int4,
        species -> Varchar,
        colors -> Varchar,
        cat_id -> Nullable<Int4>,
    }
}

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

joinable!(birds -> cats (cat_id));

allow_tables_to_appear_in_same_query!(
    birds,
    cats,
);

我可以找到的唯一与此相关的issue说我需要在范围内拥有birds并引用我提供的table!宏,所以我不确定丢失了什么

当我注释掉与birds数据库相关的所有内容时,所有内容都会按预期运行。

包含Cargo.toml的完整项目,以供参考:https://github.com/crashspringfield/prrr_gql/tree/diesel-error

1 个答案:

答案 0 :(得分:0)

如错误所述,birds不在范围内。 table!宏创建一个公共模块(birds),然后您需要将其纳入范围以能够派生Associations(在models.rs中):

use super::schema::birds;

有关示例,请参见diesel::associations,其中表明需要为use的模式derive