Создать отношение "Один к одному" в laravel
Кто может подсказать как создать связь "Один к одному" между таблицами "participants" и "users" по ключевому полю "id" ? Перерыл кучу источников и много попробовал, последний вариант попытки покажу ниже. Если кто знает как осуществить эту связь, то буду очень рад вашей помощи, спасибо!
Миграция "participants":
public function up()
{
Schema::create('participants', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('mer_id')->unsigned();
$table->bigInteger('user_id')->unsigned();
$table->string('name');
$table->timestamps();
$table->foreign('mer_id')->references('post_id')->on('posts');
});
}
Миграция "users":
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
В модели "User":
public function participants()
{
return $this->hasOne('App\Participant', 'user_id', 'id');
}
В модели "Participant":
public function user()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
Спасибо!
Ответы (1 шт):
Автор решения: Alexandr Revnuk
→ Ссылка
Миграция "participants":
public function up()
{
Schema::create('participants', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('name');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
Миграция "users":
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
В модели "User":
public function participant()
{
return $this->hasOne(Participant::class);
}
В модели "Participant":
public function user()
{
return $this->belongsTo(User::class);
}
Первой - миграция юзера, второй - вторая таблица
