问题
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.
回答1:
Put the unique index only on persona_id
:
$table->unique('persona_id');
回答2:
I would just replace:
$table->integer('persona_id')->unsigned();
$table->unique(['persona_id', 'id']);
by
$table->integer('persona_id')->unique();
来源:https://stackoverflow.com/questions/49986148/laravel-one-to-one-relationship-becomes-one-to-many-relationship