我有一个函数,它接受两个可选的过滤参数,如果提供了这些参数,则过滤表中的数据。为此,我创建了一个盒装查询。我想用这个盒装查询创建一个右连接。Diesel 的当前文档没有提到 right join,但似乎更喜欢这种belonging_to
方法。我已将代码简化为一个示例:
#[macro_use] extern crate diesel;
use diesel::prelude::*;
table! {
groups (id) {
id -> Int4,
name -> Text,
}
}
table! {
user_groups (id) {
id -> Int4,
user_id -> Int4,
group_id -> Int4,
}
}
allow_tables_to_appear_in_same_query!(groups, user_groups);
#[derive(Debug, Queryable)]
struct Group {
id: i32,
name: String,
}
#[derive(Debug, Queryable, Associations)]
#[belongs_to(Group)]
struct UserGroup {
id: i32,
user_id: i32,
group_id: i32,
}
fn filter(
name: Option<&str>,
user_id: Option<i32>,
conn: &diesel::PgConnection,
) -> Result<Vec<(Group, Vec<UserGroup>)>, Box<dyn std::error::Error>> {
let mut query = groups::table
.right_join(user_groups::table.on(groups::id.eq(user_groups::group_id))) // this method does not exist
.into_boxed();
if let Some(name) = name {
query = query.filter(groups::name.eq(name));
}
if let Some(user_id) = user_id {
query = query.filter(user_groups::user_id.contains(user_id)); // so this is just a guess
}
Ok(query.get_results(conn)?)
}
fn main() {
let url = "postgres://question_usr:question_pwd:localhost:5432/question_db";
let conn = diesel::PgConnection::establish(url).unwrap();
let _ = filter(Some("groupname"), Some(4), &conn).unwrap();
}
目的是如果user_id
指定了参数,则只Groups
返回至少有一个UserGroup
这样的行user_group.user_id == user_id
。如何运行此查询?我需要以belonging_to
某种方式使用该功能吗?