Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: one to one relationship becomes one to many relationship

When I create a one-to-one relationship migration, laravel creates a one-to-many relationship.

PHP 7.1 & MySQL 5.7

The models are: Persona & User.

Persona:

public function user()
{
    return $this->hasOne('App\User', 'persona_id', 'id');
}

User:

public function persona()
{
    return $this->belongsTo('App\Persona', 'persona_id', 'id');
}

Migrations:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('persona_id')->unsigned();
    $table->foreign('persona_id')->references('id')->on('personas')->onDelete('cascade');
    $table->unique(['persona_id', 'id']);
    $table->string('email')->nullable()->unique();
    $table->string('password')->nullable();
    $table->rememberToken();
    $table->timestamps();
});


Schema::create('personas', function (Blueprint $table) {
    $table->increments('id');
    $table->string('tipo');
    $table->integer('cedula')->unsigned()->unique();
    $table->string('primer_nombre');
    $table->string('segundo_nombre')->nullable();
    $table->string('primer_apellido');
    $table->string('segundo_apellido')->nullable();
    /* Agregar demas campos que se requieran */
    $table->timestamps();
});

How can I make the relationship created in the database one by one and not one to many? Currently this is allowing me to save more than one user per person.

Thanks.

like image 572
Cristian David Home Acosta Avatar asked Nov 21 '25 03:11

Cristian David Home Acosta


1 Answers

Put the unique index only on persona_id:

$table->unique('persona_id');
like image 60
Jonas Staudenmeir Avatar answered Nov 22 '25 17:11

Jonas Staudenmeir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!