You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Diesel框架中belonging_to函数无法调用的问题求助

问题

在学习Diesel入门Demo,为用户和帖子添加关联关系时,调用belonging_to()函数出现以下错误:

no function or associated item named `belonging_to` found for struct `diesel_demo::models::Post` in the current scope
function or associated item not found in `diesel_demo::models::Post`

已在Post结构体上使用Associations宏,但belonging_to函数仍不可用,相关代码及错误信息如下:

查询代码

#[macro_use] extern crate diesel_demo;

use diesel::prelude::*;
use crate::diesel_demo::*;
use crate::diesel_demo::models::*;

fn main() {
    use diesel_demo::schema::posts::dsl::*;
    use diesel_demo::schema::users::dsl::*;

    let connection = establish_connection();
    let test_id = 2;
    let user = users.find(test_id).first::<User>(&connection).expect("error getting user");
    
    let post_list = Post::belonging_to(&user)
        .load::<Post>(&connection)
        .expect("Error loading user posts");

    println!("{:?}", post_list);

}

models.rs代码

use super::schema::{posts, users};

#[derive(Identifiable, Queryable, PartialEq, Debug)]
#[diesel(table_name = users)]
pub struct User {
    pub id: i32,
    pub name: String,
}

#[derive(Insertable)]
#[table_name = "users"]
pub struct NewUser<'a>{
    pub name: &'a str,
}


#[derive(Identifiable, Associations, Queryable, PartialEq, Debug)]
#[diesel(belongs_to(User))]
pub struct Post {
    pub id: i32,
    pub user_id: i32,
    pub title: String,
    pub body: String,
    pub published: bool,
}

#[derive(Insertable)]
#[table_name = "posts"]
pub struct NewPost<'a>{
    pub user_id: &'a i32,
    pub title: &'a str,
    pub body: &'a str,
    pub published: &'a bool,
}

cargo check错误信息

error[E0599]: no function or associated item named `belonging_to` found for struct `diesel_demo::models::Post` in the current scope
  --> src/bin/publish_post.rs:18:27
   |
18 |     let post_list = Post::belonging_to(&user)
   |                           ^^^^^^^^^^^^ function or associated item not found in `diesel_demo::models::Post`
解决方案

belonging_to是Diesel的Associations trait提供的方法,仅在结构体上添加Associations宏还不够,需要显式导入该trait才能让方法在当前作用域可见。

修改查询代码的导入部分,新增Associations的导入:

use diesel::prelude::*;
use diesel::associations::Associations; // 新增此行
use crate::diesel_demo::*;
use crate::diesel_demo::models::*;

完成导入后,Post::belonging_to(&user)就能正常编译执行了。

内容的提问来源于stack exchange,提问作者Troybit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 13:17:01