【问题标题】:How could I find a value using a column other than the primary key with Diesel?如何使用 Diesel 的主键以外的列找到值?
【发布时间】:2021-04-19 18:12:00
【问题描述】:

我有一个用户表,并希望使用 Diesel 执行搜索,以确保该用户名尚未被使用。我发现执行查询的唯一方法是使用find() 函数,它使用主键。有没有类似SELECT * FROM users WHERE username = foo的使用其他字段搜索的功能?

这是我的用户表:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE TABLE users (
    user_id uuid PRIMARY KEY DEFAULT uuid_generate_v4() NOT NULL UNIQUE,
    username VARCHAR(255) NOT NULL UNIQUE,
    password VARCHAR(60) NOT NULL
);

这是我正在使用的 Rust 结构:

#[derive(Queryable, AsChangeset, Deserialize, Serialize)]
#[table_name = "users"]
pub struct User {
    pub user_id: uuid::Uuid,
    pub username: String,
    pub password: String,
}

#[derive(Insertable, Deserialize, Serialize)]
#[table_name = "users"]
pub struct InsertableUser {
    pub username: String,
    pub password: String,
}

【问题讨论】:

标签: rust rust-diesel


【解决方案1】:

Diesel 提供了一个通用的.filter 方法,让您可以构建任意复杂的 where 子句。 对于您的示例查询,您可以查找以下内容:

users::table.filter(users::username.eq("foo"))

【讨论】:

    猜你喜欢
    • 2019-02-16
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2013-05-12
    相关资源
    最近更新 更多