首页 > 解决方案 > Laravel - errno:150 外键约束的格式不正确

问题描述

我想在公司模型和工作模型之间建立关系但这给了我这个错误:

PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `my-career`.`#sql-2fd8_ba` (errno: 150 "Foreign key constraint is incorrectly formed")")

公司型号:

class Company extends Model{
    public $table="comppanies";
    public function jobs() {
        return $this->hasMany(App\Job::class);
    }
}

工作模式:

class Job extends Model{
    public $table="jobs";
    public function company() {
        return $this->belongsTo(App\Company::class, 'company_id');
    }
}

工作表:

public function up()
{
    Schema::create('jobs', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('company_id')->unsigned();
        $table->foreign('company_id')->references('id')->on('company');
    });
}

我不知道问题出在哪里

标签: phplaravellaravel-5

解决方案


comppanies您应该在参考源中使用表名,因此:

$table->foreign('company_id')->references('id')->on('company');

应该 :

$table->foreign('company_id')->references('id')->on('comppanies');
_____________________________________________________^^^^^^^^^^

推荐阅读