How to get a single object from Diesel join

Hello. Working with rust 1.83, diesel 2.2.5. I have two tables (animal & plan), the first has a foreign key (plan_id) to the second. The tables are modeled with structs. I can do a simple query on the 'animal' table and get back a populated Animal:

fn get_animal(target_id: i32) -> Vec<Animal> {
    use crate::schema::animal::dsl::*;

    let conn = &mut crate::establish_connection();

    let animals = animal
        .find(target_id)
        .select(Animal::as_select())
        .load::<Animal>(conn)
        .expect("Error loading animal!");

    animals
}

However, when I look for examples on how to do a left join between the tables, I only see examples which return two objects. I want to get an 'Animal' back with the 'plan' field of 'Animal' populated with the 'name' field of the corresponding 'Plan', Rather than an 'Animal', and a 'Plan'. If I was writing straight SQL, I could do something like this:

select animal.*, plan.name as plan from animal 
left join "plan" on plan.id = animal.plan_id

Any pointers? Thanks!

Does using a VIEW work? For example,

CREATE VIEW complete_animal AS SELECT
    animal.*,
    plan.name AS plan
FROM
    animal
LEFT JOIN
    plan ON plan.id = animal.plan_id;

Then you'll be able to define a table! as normal for the complete animal, and, more importantly, you'll be able to leave the structs that you use to insert into these tables alone.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.