TGViewer
PHP | Вопросы собесов PHP | Вопросы собесов @easy_php_ru · 2.31K subscribers
Post #2115 545
🤔 Как типы связи реализуются в Larevel?

В Laravel связи между моделями реализуются через Eloquent ORM. Eloquent предоставляет удобные методы для работы с отношениями (relations) между таблицами в базе данных.

🚩Один к одному (`One to One`)
Каждая модель User имеет один Profile.
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}


В модели Profile
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}


Теперь можно получить профиль пользователя так
$user = User::find(1);
$profile = $user->profile; // Получаем профиль пользователя


🟠Один ко многим (`One to Many`)
Каждый Post может иметь много Comment.
В модели Post
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}


В модели Comment
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}


Теперь можно получить все комментарии к посту:
$post = Post::find(1);
$comments = $post->comments; // Коллекция комментариев


🟠Многие ко многим (`Many to Many`)
Каждый User может подписаться на несколько Role, и наоборот.
В Laravel для связи многие ко многим нужна промежуточная таблица role_user (название должно быть singular_singular в алфавитном порядке).
В модели User
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}


В модели Role
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}


Теперь можно получить роли пользователя:
$user = User::find(1);
$roles = $user->roles;


Добавить роль:
$user->roles()->attach($roleId);


Удалить роль
$user->roles()->detach($roleId);


Синхронизировать (удалить старые и добавить новые):
$user->roles()->sync([1, 2, 3]);


🟠Связь через другую таблицу (`Has One / Has Many Through`)
Например, у нас есть Country, User, Post. Мы хотим получить все посты в стране.
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(Post::class, User::class);
}
}


Теперь можно получить все посты страны
$country = Country::find(1);
$posts = $country->posts;


🟠Полиморфные связи (`Polymorphic Relations`)
Позволяет разным моделям использовать одну таблицу для хранения данных.

Пример: у нас есть Post и Video, к которым могут быть Comment
В модели Comment
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}


В модели Post
class Post extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}


В модели Video
class Video extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}


Использование
$post = Post::find(1);
$post->comments()->create(['content' => 'Отличный пост!']);

$video = Video::find(1);
$video->comments()->create(['content' => 'Крутое видео!']);


Ставь 👍 и забирай 📚 Базу знаний
  • 👍 2
More from @easy_php_ru
  1. Oct 13, 2026Post #2477
  2. Oct 13, 2026🤔 Что такое namespaces Namespaces в PHP — это способ организации кода для предотвращения…
  3. Oct 13, 2026🤔 Чем отличается Require от Includ'а? В PHP есть две схожие конструкции для подключения ф…
  4. Oct 13, 2026Post #2474
  5. Oct 12, 2026🤔 Что такое инкремент и декремент? Инкремент (`++`) и декремент (`--`) — это операции в P…
  6. Oct 12, 2026🤔 Как устроен типичный тест на opening point? Тест на Opening Point (OP-тест) используетс…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →