简体   繁体   中英

How to create One to many relationship between two table in php Laravel?

Im trying to make the One to Many relationship for example I have two tables Groups and AllotmentApps. Groups table has only two column(GrpId,Name). AllotmentApp has many columns(Id,StudentName, FatherName and many more including a Foreign key(GrpId from the group table). I want to make a relation "A group have many or exacly 3 Application, but but more than one application can belongs to the same GrpId. I've write code but giving me error:

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.

Groups Table Code:

<?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');
    }
}

Group Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

AllotmentApps Table

<?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');
    }
}

Allotment Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class AllotmentApps extends Model
{
    //

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

Where I am wrong kindly help me.

Try the following code

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

}

The problem: You use bigIncrements, which is an UNSIGNED BIGINT on the Groups table and an UNSIGNED INTEGER as a foreign key on the AllotmentApps table. These have to be of the same type. You can either change the UNSIGNED BIGINT on the Groups table to UNSIGNED INTEGER or vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM