Models
A model maps a database row to a PHP object. Extend Atom\Database\Model and describe the mapping with attributes. Atom uses the configured database connection to load and save the model.
Map a model to a table
#[Table] names the table, #[Column] maps a property to a column, and #[PrimaryKey] identifies the row. This example assumes the products table already exists and the database generates its integer IDs. Create or change the table with a migration.
<?php
namespace App\Models;
use Atom\Database\Model;
use Atom\Database\Orm\Attributes\Column;
use Atom\Database\Orm\Attributes\PrimaryKey;
use Atom\Database\Orm\Attributes\Table;
#[Table("products")]
final class Product extends Model
{
#[PrimaryKey("id")]
public int $id;
#[Column("name")]
public string $name;
#[Column("price")]
public int $price;
}
The snippets below assume App\Models\Product is imported.
Find a record
Use find() with a primary key. It returns a model instance or null if there is no matching row.
$product = Product::find(42);
Save a record
Create a model, assign its values, and call save() to insert the row. Atom fills the generated ID on the model.
$product = new Product();
$product->name = "Desk lamp";
$product->price = 24;
$product->save();
To update an existing row, load it first, change its properties, and save it again. Atom uses the primary key to identify the row to update.
$product = Product::find(42);
if ($product !== null) {
$product->price = 28;
$product->save();
}
Delete a record
Call delete() on a loaded model to delete the row identified by its primary key.
$product = Product::find(42);
if ($product !== null) {
$product->delete();
}
See Relations when a model needs to load records from related tables.