使用生锈柴油时如何进行计数查询

how to do a count query when using rust diesel

我正在使用 rust 1.59.0 柴油 diesel = { version = "1.4.8", features = ["postgres","64-column-tables","chrono"] } 进行计数查询 document,这是我的代码现在的样子:

use diesel::{ExpressionMethods, QueryDsl, QueryResult, RunQueryDsl};
use diesel::dsl::count;
use rocket::serde::json::Json;
use rust_wheel::config::db::config;

pub fn channel_fav_count(req_channel_id: &i64) -> i32 {
    use crate::model::diesel::dolphin::dolphin_schema::article_favorites::dsl::*;
    let connection = config::establish_connection();
    let query = article_favorites
        .filter(channel_id.eq(req_channel_id));
    let query_result = query.select(count(id)).first(&connection);
    return query_result.unwrap_or(0);
}

当我编译代码时,显示如下错误:

error[E0277]: the trait bound `i32: FromSql<BigInt, Pg>` is not satisfied
    --> src/service/app/cruise/article/article_fav_service.rs:11:48
     |
11   |     let query_result = query.select(count(id)).first(&connection);
     |                                                ^^^^^ the trait `FromSql<BigInt, Pg>` is not implemented for `i32`

为什么会这样?我应该怎么做才能解决这个问题?

首先你必须知道它是查询计数return i64 不是 i32,所以你必须自己将 i64 转换为 i32

可能是这样

let query_result = query.select(count(id)).first(&connection).map(|x| x as i32);

您也可以通过如下过滤查询获得计数

users
    .filter(user_id.eq(_user_id))
    .count()
    .get_result(conn) // Result<i64, Error>

你的代码是这样的

article_favorites
    .filter(channel_id.eq(req_channel_id))
    .count()
    .get_result(&connection)