Models and Relationships
Part 2 · Laravel Rust. Turn the café's database tables into typed Rust structs with #[model], connect them with #[belongs_to] and #[has_many], and meet enum and JSON columns.
In the last lesson you built the café’s menu_items, orders and order_items tables. They exist in the database, but your Rust code can’t see them yet. In this lesson you’ll create a model for each table: a plain Rust struct that Laravel Rust knows how to read from and write to the database. You’ll also teach the models how they relate to each other, so “the items in this order” becomes one line of code.
What is a model?
A model is a Rust struct that stands for one database table. Each field on the struct matches a column, and each instance of the struct is one row.
Think of the table as a stack of identical paper forms, and the model as the blank form template. Load a row and you get a filled-in form you can read in Rust, with real Rust types.
This style of tool is called an ORM (object-relational mapper): it maps rows to structs and back so you rarely write SQL by hand. Laravel Rust checks your column names, relationships and types at compile time, so many mistakes never make it to a running app.
Note
Everything here follows the official Models guide (opens in new tab) and Relationships guide (opens in new tab). Laravel Rust is new, so those pages are the source of truth if anything changes.
Your first model
Models live in src/models/, one file per model, next to the User model your app already has. Here is the café’s menu item:
use laravel::model::model;use laravel::time::Timestamp;
#[model]pub struct MenuItem { pub id: i64, pub name: String, pub description: Option<String>, pub price_cents: i64, #[default] pub available: bool, pub created_at: Timestamp, pub updated_at: Timestamp,}Let’s read it slowly:
#[model]is an attribute macro (you met these in Macros and Attributes). It generates all the database code:MenuItem::query(),MenuItem::find(), and more. It also derivesClone,DebugandSerialize, so don’t add those yourself.pub id: i64is the primary key. Theid()column from the migration is a big integer, which Rust reads asi64. Database integers are signed (they could hold negative numbers), so the official docs usei64for model ids and foreign keys likeuser_id, even though real ids are always positive.pub name: Stringmatches thestring("name")column.pub description: Option<String>matches a nullable column. ANULLin the database becomesNonein Rust, exactly like theOptionfrom Option and Result.pub price_cents: i64holds whole cents. The schema builder’s integer columns read back asi64(or a smaller integer likei32).#[default] pub available: boolmarks a column with a database default (.default(true)in the migration). You may leave it out when creating a menu item, and you’ll get the database’s value back.created_atandupdated_atmatchtable.timestamps(). Laravel fills them in on create and refreshesupdated_aton every update.
Tip
After adding the file, declare it in src/models/mod.rs the same way the existing User model is declared, so you can write use crate::models::MenuItem; anywhere in your app.
How Laravel finds the table
You never told MenuItem which table to use. Laravel follows conventions:
| What | Convention | Example |
|---|---|---|
| Table | Struct name in snake_case, made plural | MenuItem → menu_items |
| Primary key | The id field |
id |
| Column | The field’s name | price_cents → price_cents |
If your table breaks a convention, you can override it, for example #[model(table = "drinks")] on the struct or #[column("is_available")] on a field. Following the conventions means less to write.
Creating a menu item
With the model in place, adding a row takes one macro, create!:
use laravel::model::create;
use crate::models::MenuItem;
let flat_white = create!(MenuItem { name: "Flat White", price_cents: 400 }).await?;
println!("Saved with id {}", flat_white.id);create!looks like a struct literal, and each field sets the column with the same name.- We skipped
id,description,availableand the timestamps. The database assigns theid,descriptionbecomesNULL,availabletakes its default, and Laravel fills in the timestamps. &strvalues like"Flat White"are accepted forStringcolumns..await?runs the insert and gives back the stored model, complete with its newid.
What if you forget a required column, like price_cents? Every non-nullable column without #[default] is required, so the code doesn’t compile. The error names the missing field, roughly like this:
error[E0080]: evaluation panicked: can't create a `MenuItem` without `price_cents`That’s a bug caught on your laptop instead of in front of a customer.
Relationships: connecting the tables
Tables point at each other with foreign keys. Models express the same links with relationship fields. There are two you’ll use constantly:
- belongs to: “this order item belongs to one menu item.” The foreign key (
menu_item_id) lives on this table. - has many: “this order has many items.” The foreign key (
order_id) lives on the other table.
They are two sides of the same link, like a child holding a parent’s hand: the order has many items, and each item belongs to an order.
use laravel::model::{BelongsTo, model};use laravel::time::Timestamp;
use crate::models::{MenuItem, Order};
#[model]pub struct OrderItem { pub id: i64, pub order_id: i64, pub menu_item_id: i64, pub quantity: i64, pub unit_price_cents: i64, pub created_at: Timestamp, pub updated_at: Timestamp,
#[belongs_to] pub order: BelongsTo<Order>, #[belongs_to] pub menu_item: BelongsTo<MenuItem>,}- The plain fields (
order_id,menu_item_id, …) are the real columns. #[belongs_to] pub order: BelongsTo<Order>is not a column. It declares a relationship. Laravel adds_idto the field name, soorderuses theorder_idcolumn.menu_itemlikewise usesmenu_item_id.
Now the order side:
use laravel::model::{BelongsTo, HasMany, model};use laravel::time::Timestamp;
use crate::models::{OrderItem, User};
#[model]pub struct Order { pub id: i64, pub user_id: i64, pub customer_name: String, #[default] pub total_cents: i64, pub note: Option<String>, pub created_at: Timestamp, pub updated_at: Timestamp,
#[belongs_to] pub user: BelongsTo<User>, #[has_many] pub items: HasMany<OrderItem>,}#[has_many] pub items: HasMany<OrderItem> says “an order has many order items”. For has-many, Laravel looks for a foreign key on the child table named after the parent struct plus _id. The parent is Order, so it uses order_items.order_id. That’s why the field can be called items while the column is still order_id.
You can add the reverse links too: #[has_many] pub orders: HasMany<Order> on User, and #[has_many] pub order_items: HasMany<OrderItem> on MenuItem.
Warning
Relationship fields start out unloaded. Reading order.items before loading it panics with a message telling you which .with(...) to add. That’s deliberate, and it protects you from a classic performance trap. You’ll learn how to load relationships properly in the next lesson.
A relationship also lets create! fill in foreign keys for you. Pass the related model instead of a raw id:
let order = create!(Order { customer_name: "Sam", user: &user }).await?;user: &user sets user_id from the user’s key, so you can’t mix up two numbers by accident.
Smarter column types
Columns don’t have to be plain numbers and text. Laravel Rust supports a few richer types. Here is a light tour.
Enum columns (db::Enum)
An order’s status is one of a few fixed choices. A Rust enum (from Enums and match) is perfect for that. Derive Enum and Laravel stores each variant as text in the column:
use laravel::prelude::*;use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Enum)]#[serde(rename_all = "snake_case")]pub enum OrderStatus { Pending, Preparing, Ready, PickedUp,}Enum(from the prelude) teaches Laravel to read and write this type as a column.#[serde(rename_all = "snake_case")]decides the stored text:PickedUpis saved as"picked_up".- Add
#[default] pub status: OrderStatus,to theOrderstruct, and thestatuscolumn (default"pending") now reads back as a real enum. A typo like"redy"can never sneak into your code.
JSON columns (db::Json)
Some data has a shape of its own, like a customer’s saved drink preferences. Derive db::Json on a struct, back it with a json column (table.json("preferences") in a migration), and use it as a field:
use laravel::db;use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, db::Json)]pub struct DrinkPreferences { pub milk: String, pub extra_shot: bool,}On a User model you’d add pub preferences: DrinkPreferences,. Laravel turns the struct into JSON when saving and back into Rust when loading.
Values across several columns (db::Embed)
Sometimes one idea spans several columns. If the café went international, a price would need an amount and a currency. Deriving db::Embed on a Money { amount, currency } struct and marking an order field #[embed] pub total: Money maps it onto two columns, total_amount and total_currency. You won’t need this yet; just know it exists.
Try it yourself
- Write a
LoyaltyCardmodel for theloyalty_cardstable from the last lesson’s exercise (id,user_id,stampswith a default of0, timestamps). Give it auserrelationship. - Using
create!, give the logged-inusera new loyalty card without writinguser_idorstampsyourself.
Show solution
use laravel::model::{BelongsTo, model};use laravel::time::Timestamp;
use crate::models::User;
#[model]pub struct LoyaltyCard { pub id: i64, pub user_id: i64, #[default] pub stamps: i64, pub created_at: Timestamp, pub updated_at: Timestamp,
#[belongs_to] pub user: BelongsTo<User>,}let card = create!(LoyaltyCard { user: &user }).await?;user: &user fills user_id, #[default] lets the database set stamps to 0, and the table name loyalty_cards comes from the struct name.
Recap
- A model is a struct marked
#[model]: fields are columns, instances are rows, andOption<T>marks nullable columns. - Conventions map
MenuItemto themenu_itemstable and fields to same-named columns. #[default]marks columns with a database default; missing required columns fail at compile time.#[belongs_to](foreign key on this table) and#[has_many](foreign key on the other table) connect models.- Richer columns are available:
Enumfor fixed choices,db::Jsonfor structured data, anddb::Embedfor values spread over several columns.
What’s next
You can describe the data; now let’s ask questions of it. In Querying Models you’ll filter the menu with compile-checked conditions and load relationships without slowing the café’s site down.
0 of 35 lessons complete