Отношения

Один-к-Одному
users
    id
    name
    
profiles
    id
    user_id
    title
class User extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}
class Profile extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
Один-ко-Многим
brands
    id
    name
    
products
    id
    brand_id
    name
class Brand extends Model
{
    public function products()
    {
      return $this->hasMany(Product::class);
    }
}
class Product extends Model
{
    public function brand()
    {
      return $this->belongsTo(Brand::class);
    }
}
Многие через отношение

mechanic hasMany cars cars hasMany owners значит можно достать всех владельцев всех машин конкретного механика mechanic hasManyThrough(Owner::class,Car::class);

mechanics
    id
    name
    
cars
    id
    model
    mechanic_id

owners
    id
    name 
    car_id
class Mechanic extends Model
{
    public function carOwners()
    {
        return $this->hasManyThrough(Owner::class,Car::class);
    }
}
Многие-ко-Многим
categories
    id
    name
    
products
    id
    name
    
category_product
    id
    category_id
    product_id
class Category extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
}
class Product extends Model
{
    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }
}

Last updated