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

Posted

技术标签:

【中文标题】如何在 php Laravel 中的两个表之间创建一对多关系?【英文标题】:How to create One to many relationship between two table in php Laravel? 【发布时间】:2020-04-15 07:42:44 【问题描述】:

我试图建立一对多的关系,例如我有两个表 Groups 和 AllotmentApps。 Groups 表只有两列(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');
    

哪里错了,请帮帮我。

【问题讨论】:

【参考方案1】:

问题:您使用 bigIncrements,它是 Groups 表上的 UNSIGNED BIGINT,而 UNSIGNED INTEGER 作为 AllotmentApps 表上的外键。这些必须是同一类型。您可以将 Groups 表中的 UNSIGNED BIGINT 更改为 UNSIGNED INTEGER,反之亦然。

【讨论】:

【参考方案2】:

试试下面的代码

public function up()

Schema::create('AllotmentApps', function (Blueprint $table) 

    $table->unsignedBigInteger('grpID');
    $table->foreign('grpID') ->references('id')->on('groups')- 
    >onupdate('cascade');
);

【讨论】:

以上是关于如何在 php Laravel 中的两个表之间创建一对多关系?的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 中两个不同数据库之间的匹配 ID

如何填充与laravel中的产品表链接的类别表

laravel 雄辩的数据透视表查询“不明确的列名”

如何在 Laravel 中的表之间建立关系?

如何在 FMDB 中的两个表之间创建或稳定关系?

Laravel 加入 Auth 表