Relations

A relation tells Atom how two models connect. Here products.category_id points to categories.id. From the product side, a product belongs to one category. From the category side, a category can have many products.

Define a belongs-to relation

Extend the Product model with a mapped foreign key and a separate property for the related object. Add the BelongsTo import at the top of the file and the two properties inside Product.

app/Models/Product.php (excerpt)
use Atom\Database\Orm\Attributes\BelongsTo;

// Inside Product.
#[Column("category_id")]
public ?int $categoryId = null;

#[BelongsTo(Category::class, foreignKey: "category_id")]
public ?Category $category = null;

$categoryId stores the database key. $category holds the loaded Category object. The relation's foreignKey names the database column.

Define a has-many relation

On Category, declare a collection with #[HasMany]. Atom matches categories.id to products.category_id.

app/Models/Category.php
<?php

namespace App\Models;

use Atom\Database\Model;
use Atom\Database\Orm\Attributes\Column;
use Atom\Database\Orm\Attributes\HasMany;
use Atom\Database\Orm\Attributes\PrimaryKey;
use Atom\Database\Orm\Attributes\Table;

#[Table("categories")]
final class Category extends Model
{
    #[PrimaryKey("id")]
    public int $id;

    #[Column("name")]
    public string $name;

    /** @var list<Product> */
    #[HasMany(Product::class, foreignKey: "category_id", localKey: "id")]
    public array $products = [];
}

Use with() with the PHP relation property name. Atom loads the related records for the result set together, so the loop can read the objects already assigned to each model.

$products = Product::query()->with("category")->orderBy("id")->all();

foreach ($products as $product) {
    $categoryName = $product->category?->name ?? "Uncategorized";
}

To load the products for one category, pass the relation name to find(). A category with no products has an empty $products collection.

$category = Category::find(1, "products");
$products = $category?->products ?? [];