Aeros supports model relationships through pivot tables, allowing you to define connections between different models. All relationships use a pivot table approach with automatic table name detection.
class User extends Model{ public function roles() { return $this->belongsToMany(Role::class); }}class Role extends Model{ public function users() { return $this->belongsToMany(User::class); }}
class Country extends Model{ public function posts() { return $this->hasManyThrough( Post::class, // Final model User::class // Intermediate model ); }}
$country = Country::find(1);// Get all posts from this country$posts = $country->posts()->get();foreach ($posts as $post) { echo $post->title;}// With constraints$publishedPosts = $country->posts() ->where('status', 'published') ->get();
public function posts(){ return $this->hasManyThrough( Post::class, User::class, 'country_id', // Foreign key on users table 'user_id', // Foreign key on posts table 'id', // Local key on countries table 'id' // Local key on users table );}
// ❌ N+1 Problem (1 + N queries)$users = User::query()->get();foreach ($users as $user) { echo $user->profile->bio; // Separate query for each user}// ✅ Eager Loading (2 queries)$users = User::with('profile')->query()->get();foreach ($users as $user) { echo $user->profile->bio; // No additional query}
$user = User::find(1);// Load if not already loaded$user->load('posts');// Reload even if loaded$user->reload('posts');// Load multiple$user->loadMany(['posts', 'roles']);
class User extends Model{ public function posts() { return $this->hasMany(Post::class); } public function roles() { return $this->belongsToMany(Role::class); }}class Post extends Model{ public function author() { return $this->belongsTo(User::class); } public function tags() { return $this->belongsToMany(Tag::class); } public function comments() { return $this->hasMany(Comment::class); }}
class Customer extends Model{ public function orders() { return $this->hasMany(Order::class); } public function address() { return $this->hasOne(Address::class); }}class Product extends Model{ public function categories() { return $this->belongsToMany(Category::class); } public function orders() { return $this->belongsToMany(Order::class) ->withPivot(['quantity', 'price']); }}
CREATE TABLE role_user ( id INTEGER PRIMARY KEY AUTOINCREMENT, role_id INTEGER NOT NULL, user_id INTEGER NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(role_id, user_id));CREATE INDEX idx_role_user_role_id ON role_user(role_id);CREATE INDEX idx_role_user_user_id ON role_user(user_id);