本文介绍了Laravel:一对一关系变成一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我创建一对一的关系迁移时,laravel创建一对多的关系。
When I create a one-to-one relationship migration, laravel creates a one-to-many relationship.
PHP 7.1& MySQL 5.7
PHP 7.1 & MySQL 5.7
模型是:Persona&用户。
The models are: Persona & User.
角色:
public function user()
{
return $this->hasOne('App\User', 'persona_id', 'id');
}
用户:
public function persona()
{
return $this->belongsTo('App\Persona', 'persona_id', 'id');
}
迁移:
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.
谢谢。
推荐答案
仅在 persona_id
上放置唯一索引:
$table->unique('persona_id');
这篇关于Laravel:一对一关系变成一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!