【问题标题】:Laravel: one to one relationship becomes one to many relationshipLaravel:一对一关系变成一对多关系
【发布时间】:2018-10-03 19:09:23
【问题描述】:

当我创建一对一的关系迁移时,laravel 会创建一个一对多的关系。

PHP 7.1 和 MySQL 5.7

模型是:角色和用户。

角色:

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();
});

如何让数据库中创建的关系是一对一而不是一对多? 目前,这允许我每人保存多个用户。

谢谢。

【问题讨论】:

    标签: php mysql laravel-5 migration entity-relationship


    【解决方案1】:

    仅将唯一索引放在persona_id

    $table->unique('persona_id');
    

    【讨论】:

    • 我没有这样想。谢谢。
    【解决方案2】:

    我只想替换:

    $table->integer('persona_id')->unsigned();
    $table->unique(['persona_id', 'id']);
    

    通过

    $table->integer('persona_id')->unique();
    

    【讨论】:

      猜你喜欢
      • 2018-09-27
      • 2018-06-15
      • 1970-01-01
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多