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

Миграции для моделей
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();
    });
}

Last updated