如何在php Laravel中创建两个表之间的一对多关系?

时间:2020-04-15 07:42:44

标签: php mysql laravel

例如,我尝试建立一对多关系,我有两个表Groups和AllotmentApps。组表只有两列(GrpId,Name)。 AllotmentApp具有许多列(Id,StudentName,FatherName,以及更多列,包括外键(来自组表的GrpId))。 我想建立一个关系“一个组有很多或全部3个应用程序,但是一个同一个GrpId可以属于多个应用程序。 我已经编写了代码,但给了我错误:

SQLSTATE[HY000]: General error: 1005 Can't create table `has`.`allotmentapps` (errno: 150 "**Foreign key constraint is incorrectly formed")** (SQL: alter table `AllotmentApps` add constraint `allotmentapps_grpid_foreign` foreign key (`grpID`) references `groups` (`id`) on delete cascade)

  at C:\xampp\htdocs\HAS\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
    665|         // If an exception occurs when attempting to run a query, we'll format the error
    666|         // message to include the bindings with SQL, which will make this exception a
    667|         // lot more helpful to the developer instead of just the database's errors.
    668|         catch (Exception $e) {
  > 669|             throw new QueryException(
    670|                 $query, $this->prepareBindings($bindings), $e
    671|             );
    672|         }
    673|

  **Exception trace:**

  **1**   **PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `has`.`allotmentapps` (errno: 150 "Foreign key constraint is incorrectly formed")")
      C:\xampp\htdocs\HAS\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
  2   PDOStatement::execute()
      C:\xampp\htdocs\HAS\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463**

  Please use the argument -v to see more details.

组表代码:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGroupsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('groups', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('groups');
    }
}

组模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Groups extends Model
{
    //
    public function llotmentApps()
    {
        return $this->hasMany('App\AllotmentApps');
    }
}

AllotmentApps表

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAllotmentAppsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('AllotmentApps', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('sname');
            $table->string('fname');
            $table->string('Roll_No')->unique();
            $table->string('Department');
            $table->integer('cnic');
            $table->string('domicile');
            $table->double('cgpa');
            $table->string('Session');
            $table->string('degreeProgram');
            $table->integer('contactNo');
            $table->integer('GcontactNo');
            $table->string('preAddress');
            $table->string('permAddress');
            $table->integer('challanNo');
            $table->integer('fee');
            $table->integer('grpID')->unsigned();
            $table->foreign('grpID') ->references('id')->on('groups')->onDelete('cascade')->onupdate('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('AllotmentApps');
    }
}

分配模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class AllotmentApps extends Model
{
    //

     public function groups()
    {
        return $this->belongsTo('App\Groups');
    }
}

如果我错了,请帮助我。

2 个答案:

答案 0 :(得分:0)

尝试以下代码

public function up()
{
Schema::create('AllotmentApps', function (Blueprint $table) 
{
    $table->unsignedBigInteger('grpID');
    $table->foreign('grpID') ->references('id')->on('groups')- 
    >onupdate('cascade');
});

}

答案 1 :(得分:0)

问题:您使用bigIncrements,它是Groups表上的UNSIGNED BIGINT,而Unalloced INTEGER是AllotmentApps表上的外键。这些必须是相同的类型。您可以将“组”表上的“未签名的大号”更改为“未签名的整数”,反之亦然。

相关问题