如何使用柴油进行 IN 查询?

How to do a IN query using diesel?

我想使用 PostgreSQL 13 到 select 一些 id 集合中的歌曲 table 中的歌曲集合对 diesel 进行 IN 查询。数据库执行的SQL可能是这样的:

select * from songs where id in(1,2,3)

我尝试使用像这样的生锈柴油方式做的事情:

pub fn songs(ids: Vec<i64>){
    use schema::songs::dsl::*;
    let connection = config::establish_connection();
    let results = songs.filter(id.contains(ids))
        .load::<QuerySongs>(&connection)
        .expect("Error loading posts");
}

似乎没有用,当我使用 cargo build 编译项目代码时显示如下错误:

error[E0599]: the method `contains` exists for struct `songs::schema::songs::columns::id`, but its trait bounds were not satisfied
  --> src/biz/music/songs.rs:37:35
   |
37 |       let results = songs.filter(id.contains(ids))
   |                                     ^^^^^^^^ method cannot be called on `songs::schema::songs::columns::id` due to unsatisfied trait bounds

我读了docs and source code demo but it was so short and did not mention about how to execute a query by id in a collection. What should I do to make a IN query in rust diesel(diesel = { version = "1.4.4", features = ["postgres"] })? Here is a minimal reproducible demo

您正在寻找 .eq_any()。但请注意文档:

Creates a SQL IN statement.

Queries using this method will not be placed in the prepared statement cache. On PostgreSQL, you should use eq(any()) instead. This method may change in the future to automatically perform = ANY on PostgreSQL.

所以使用 .eq() and any() 你的代码应该类似于:

let results = songs.filter(id.eq(any(ids)))
    .load::<QuerySongs>(&connection)
    .expect("Error loading posts");