为什么我得到:完整性约束违规:1452?

时间:2015-10-18 15:01:53

标签: laravel-5 laravel-5.1

我使用数据透视表创建了多对多关系,我可以使用->detach($id)分离记录,这很好,但是当我尝试附加时:

$criteria->criterias()->attach($criteria_id);

我收到此错误:

Next exception 'Illuminate\Database\QueryException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`forge`.`criteria_criteria`, CONSTRAINT `criteria_criteria_criteria_id_foreign` FOREIGN KEY (`criteria_id`) REFERENCES `criterias` (`id`) ON DELETE CASCADE) (SQL: insert into `criteria_criteria` (`central_criteria_id`, `criteria_id`) values (11893, 8647))' in /home/forge/default/vendor/laravel/framework/src/Illuminate/Database/Connection.php:651

我的模特:

class Criteria extends Model {

    protected $table = 'criterias';
    public $timestamps = true;


    public function criterias()
    {
        return $this->belongsToMany('App\Criteria', 'criteria_criteria', 'central_criteria_id', 'criteria_id');
    }

}

class CriteriaCriteria extends Model {
    protected $table = 'criteria_criteria';
}

而且,这是我对他们的迁移:

class CreateCriteriasTable extends Migration {

    public function up()
    {
        Schema::create('criterias', function(Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }


class CreateCriteriaCriteriaPivotTable extends Migration
{

    public function up()
    {
        Schema::create('criteria_criteria', function(Blueprint $table) {
            $table->integer('central_criteria_id')->unsigned()->index();
            $table->foreign('central_criteria_id')->references('id')->on('criterias')->onDelete('cascade');
            $table->integer('criteria_id')->unsigned()->index();
            $table->foreign('criteria_id')->references('id')->on('criterias')->onDelete('cascade');
        });
    }

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

尝试将->unsigned()->index();添加到您的迁移中,如下所示:

class CreateCriteriasTable extends Migration {

  public function up()
  {
    Schema::create('criterias', function(Blueprint $table) {
        $table->increments('id')->unsigned()->index();
        $table->timestamps();
    });
  }