👺
Cheatsheet
  • 👋My cheatsheet
  • 🐘PHP
    • Тернарные операторы
    • Замыкания в PHP
    • Таблица сравнения типов PHP
  • 🟨JS
    • JS cheat sheet
    • Тернарные операторы || ?? &&
    • Таблица сравнения типов JS
    • Область видимости в JS
    • Перебор объектов через for(key in obj)
    • Доступ к свойству через переменную []
    • this в JS
    • Конструктор, оператор "new"
    • bind привязка контекста (this)
    • Замыкания в JS ...
  • ❤️Laravel
    • Laravel websockets
    • Загрузка файлов и пути к ним
    • Vite сборка изображений
    • Vite сборка CSS и JS
    • Vite подключение jQuery
    • Vite подключение Bootstrap
    • Laravel AJAX (with jQuery)
    • Дерево категорий Laravel
    • Laravel + CK-Editor + El FInder
    • Laravel deploy
    • Laravel фасады и сервис провайдеры
    • Отношения
      • Один-к-Одному
      • Один-ко-Многим
      • Многие-ко-Многим
      • Полиморфные отношения
    • Laravel cheatsheet (MAIN)
    • Laravel cheatsheet (BIG)
      • Artisan
      • Auth
      • Blade
      • Cache
      • Composer
      • Config
      • Container
      • Cookie
      • DB
      • Environment
      • Event
      • Eloquent Model
      • File
      • Form
      • HTML
      • Helper
      • Input
      • Lang
      • Log
      • Mail
      • Pagination
      • Queue
      • Redirect
      • Request
      • Response
      • Route
      • SSH
      • Schema
      • Security
      • Session
      • String
      • URL
      • UnitTes
      • Validation
      • View
    • Laravel cheatsheet (BIG PLAIN)
  • 📕PDO
    • SELECT
    • WHERE
    • INSERT
    • UPDATE
    • DELETE
    • JOIN
    • GROUP BY
    • Дерево
    • Дерево ООП
    • Дерево в массив
  • 🐋Docker
    • Docker hub push
    • Docker offline
  • 🥤Gulp
  • 🌊jQuery
  • 🪄Composer
  • 4️⃣Composer PSR-4
  • 🍥RegEx
  • 🐙Git
  • 🧑‍💻Node js
  • 🛍️PHPStorm
  • 💻Zsh
  • 🤖Arduino
Powered by GitBook
On this page
  1. Laravel
  2. Отношения

Один-к-Одному

Last updated 2 years ago

Миграции для моделей
create-profiles-table
public function up()
    {
        Schema::create('profiles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id')->nullable();
            $table->foreign('user_id')->references('id')->on('users');
            $table->date('dob');
            $table->text('bio');
            $table->string('facebook');
            $table->string('twitter');
            $table->string('github');
            $table->timestamps();
        });
    }

Пример отношения один-к-одному User и Profile

  • User может иметь только один Profile

  • Profile может принадлежать только одному User

app/Models/Profile.php
class Profile extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
app/Models/User.php
class User extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}

Получение данных «Один-к-Одному»

// получаем профиль пренадлежащий нашему пользователю
$user = User::find(1);
$userDob = $user->profile;

Создание отношений «Один-к-Одному»

// создаём профиль
$profile = new Profile();
$profile->dob = '20-03-1999';
$profile->bio = 'A professional programmer.';
//Выбираем юзера с айди 1
$user = User::find(1);
// связываем наш профиль с пользователем и сохраняем его
$profile->user()->associate($user);
$profile->save();
// альтернативный вариант связываения профиля с бреном и его сохранение
$user->profile()->save($profile);

Удаление отношений «Один-к-Одному»

// берём родительский обьект $user
$user = User::find(1);
// и удаляем профиль связанный с этим пользователём
$user->profile()->delete();
// А если мы удалим $user перед удалением профиля, то в базе останется потерянный профиль.

Laravel предоставляет элегантный способ удаления дочерних записей при удалении родительской записи. Вы можете использовать метод onDelete() в своей миграции при определении ключа foriegn.

public function up()
{
    Schema::create('profiles', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('user_id')->nullable();
        $table->foreign('user_id')->references('id')->on('users');
        $table->date('dob');
        $table->text('bio');
        $table->string('facebook');
        $table->string('twitter');
        $table->string('github');
        $table->timestamps();
    });
}

Подробнее -

❤️
https://laravel.demiart.ru/one-to-one-relationship/