# Отношения

{% 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);
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://overfinch.gitbook.io/cheatsheet/laravel/otnosheniya.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
