> For the complete documentation index, see [llms.txt](https://overfinch.gitbook.io/cheatsheet/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://overfinch.gitbook.io/cheatsheet/laravel/otnosheniya.md).

# Отношения

{% content-ref url="/pages/hFK8nG3ZWeVA1MkzOLb7" %}
[Один-к-Одному](/cheatsheet/laravel/otnosheniya/odin-k-odnomu.md)
{% endcontent-ref %}

```xml
users
    id
    name
    
profiles
    id
    user_id
    title
```

```php
class User extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}
```

```php
class Profile extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
```

{% content-ref url="/pages/1da1hoXtZyu5EBwlarbb" %}
[Один-ко-Многим](/cheatsheet/laravel/otnosheniya/odin-ko-mnogim.md)
{% endcontent-ref %}

```
brands
    id
    name
    
products
    id
    brand_id
    name
```

```php
class Brand extends Model
{
    public function products()
    {
      return $this->hasMany(Product::class);
    }
}
```

```php
class Product extends Model
{
    public function brand()
    {
      return $this->belongsTo(Brand::class);
    }
}
```

<details>

<summary>Многие через отношение</summary>

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
```

```php
class Mechanic extends Model
{
    public function carOwners()
    {
        return $this->hasManyThrough(Owner::class,Car::class);
    }
}
```

</details>

{% content-ref url="/pages/yDWXUYLmWc5cAyCcxnsf" %}
[Многие-ко-Многим](/cheatsheet/laravel/otnosheniya/mnogie-ko-mnogim.md)
{% endcontent-ref %}

```
categories
    id
    name
    
products
    id
    name
    
category_product
    id
    category_id
    product_id
```

```php
class Category extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
}
```

```php
class Product extends Model
{
    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }
}
```
