> For the complete documentation index, see [llms.txt](https://delphinpro.gitbook.io/voyager-ru/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://delphinpro.gitbook.io/voyager-ru/bread/relationships.md).

# Отношения

## Добавление отношений

С помощью конструктора BREAD вы можете легко создавать Связи между таблицами. В нижней части страницы вы увидите новую кнопку с надписью "Create Relationship" (Создать отношения).

![](/files/-ME4urIbT3xDqrAk7Fxh)

{% hint style="info" %}
**Уведомление**\
Если вы еще не создали BREAD для таблицы, его нужно будет сначала создать, а затем вернуться после создания BREAD, чтобы добавить отношения. В противном случае вы получите уведомление, которое выглядит следующим образом.
{% endhint %}

![](/files/-ME4urIdtrvIxK1jsTES)

Таким образом, после того, как BREAD уже создан, вы сможете создать новые отношения. После того, как вы нажмете на кнопку "Create Relationship" (Создать отношения). Вы увидите новое модальное окно, которое выглядит следующим образом:

![](/files/-ME4urIez1oJnV4SPJoe)

Сначала вы укажете, к какому типу отношений это будет относиться, затем выберете таблицу, на которую вы ссылаетесь, и пространство имен, принадлежащее этой таблице. Затем вы выбираете, какая строка объединяет эти таблицы.

Вы также можете указать, какие столбцы вы хотите видеть в выпадающем списке или при множественном выборе.

Теперь Вы можете легко создавать отношения `BelongsTo`, `BelongsToMany`, `HasOne` и `hasMany` непосредственно в Voyager.

## Дополнительные опции

Если вам нужно установить дополнительные параметры для `belongsToMany` отношения, вы можете сделать это после сохранения отношения в подробном поле:

```php
{
    "foreign_pivot_key": "user_id",
    "related_pivot_key": "role_id",
    "parent_key": "id"
}
```

## Сортировка отношений

Вы можете отсортировать результаты отношений, установив объект `sort` в настройках отношений:

```php
{
    "sort": {
        "field": "my_field",
        "direction": "asc"
    }
}
```

Или

```php
{
    "sort": {
        "field": "my_field",
        "direction": "desc"
    }
}
```

Для сортировки по полю `my_field` по убыванию.

## Область видимости отношений (Scope)

Вы можете легко отфильтровать показанные опции отношений, определив [local scope](https://laravel.com/docs/eloquent#local-scopes) во внешней модели.\
Например, если вы хотите показать только активные записи, создайте область видимости типа:

```php
public function scopeActive($query)
{
    return $query->where('active', 1);
}
```

И добавьте следующее к опциям отношений:

```php
{
    "scope": "active",
}
```

Значение - это название вашего метода определения масштаба без слова `scope`.\
Значение для `scopeActive()`является `active`. Для `scopeSomeUsers()` это `someUsers`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://delphinpro.gitbook.io/voyager-ru/bread/relationships.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
