The code below that shows an example of FETCH is another example related to classes and students. Note that in one part it passes a Resource into the create method in order to return a Value and thus not have to specify a return type to deserialize into. For more information on this technique, see the page on flexible typing.
// Student model with full class details #[derive(Debug,SurrealValue)] #[allow(dead_code)] structStudentClasses{ id: RecordId, name: String, classes: Vec<DanceClass>, created_at: Datetime, }
#[tokio::main] asyncfnmain()->surrealdb::Result<()> { // Connect to the database server letdb=Surreal::new::<Ws>("localhost:8000").await?;
// Sign in into the server db.signin(Root{ username: "root".to_string(), password: "secret".to_string(), }) .await?;
// Select the namespace and database to use db.use_ns("main").use_db("main").await?;
// Create a dance class and store the result letclasses: Option<DanceClass> =db .create(DANCE) .content(DanceClass{ id: RecordId::new(DANCE,"dc101"), name: "Introduction to Dancing".to_owned(), created_at: Datetime::default(), }) .await?;
// Create a student and assign her to the previous dance class // We don't care about the result here so we don't need to // type-hint and store it. We use `Resource::from` to return // a `Value` instead and ignore it. db.create(Resource::from(STUDENT)) .content(Student{ id: RecordId::new(STUDENT,"jane"), name: "Jane Doe".to_owned(), classes: classes.into_iter().map(|class| class.id).collect(), created_at: Datetime::default(), }) .await?;
// Run a query to retrieve students and full class info letmutresults=db.query(format!("SELECT * FROM {STUDENT} FETCH classes")).await?;
// Extract the first query statement result and deserialise it as a vector of students letstudents: Vec<StudentClasses> =results.take(0)?;
// Use the result as you see fit. In this case we are simply pretty printing it. println!("Students = {:?}",students);