Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a single owned record with Diesel?

Actually I'm returing a cloned struct

pub fn matrix_first_or_create(&self, schema: String, symbol: String) -> RewardMatrix {
    ....

    let rewards = reward_matrix
        .filter(state.eq(schema.clone()))
        .filter(turn_symbol.eq(symbol.clone()))
        .limit(1)
        .load::<RewardMatrix>(&self.connection)
        .expect("Error loading posts");

    if rewards.len() > 0 {
        return rewards.get(0).unwrap().clone();
    }

    ....
}

Is this the right way to handle a result in Diesel? Can I "extract" and own the first and only result from this query?

like image 846
realtebo Avatar asked Sep 17 '25 10:09

realtebo


1 Answers

What you need here is the .first() method of the RunQueryDsl trait.

Here is an example of how it works:

let reward: RewardMatrix = reward_matrix
    .filter(state.eq(schema.clone()))
    .filter(turn_symbol.eq(symbol.clone()))
    .first(&self.connection)?;

But if your query may not return that row, it’s also good to use the .optional() method of QueryResult:

let reward: Option<RewardMatrix> = reward_matrix
    .filter(state.eq(schema.clone()))
    .filter(turn_symbol.eq(symbol.clone()))
    .first(&self.connection)
    .optional()?;
like image 134
Evgeniy Avatar answered Sep 20 '25 01:09

Evgeniy