В Laravel связи между моделями реализуются через Eloquent ORM. Eloquent предоставляет удобные методы для работы с отношениями (relations) между таблицами в базе данных.
🚩Один к одному (`One to One`)
Каждая модель
User имеет один Profile. class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
В модели
Profileclass Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Теперь можно получить профиль пользователя так
$user = User::find(1);
$profile = $user->profile; // Получаем профиль пользователя
🟠Один ко многим (`One to Many`)
Каждый
Post может иметь много Comment. В модели
Postclass Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
В модели
Commentclass 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 в алфавитном порядке). В модели
Userclass User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
В модели
Roleclass 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 В модели
Commentclass Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
В модели
Postclass Post extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
В модели
Videoclass 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' => 'Крутое видео!']);
Ставь 👍 и забирай 📚 Базу знаний