php - Laravel Eloquent 创建方法导致完整性约束违规

标签 php mysql laravel eloquent

我已经建立了以下 Eloquent 模型和关系:

申请人

class Applicant {
    public function application()
    {
        return $this->hasOne(Application::class);
    }
}

申请

class Application {
    public function applicant()
    {
        return $this->belongsTo(Applicant::class);
    }

    protected $fillable = [
        // ... other fields
        'applicant_id',
    ];
}

以及他们的迁移:

申请人

public function up()
{
    Schema::create('applicants', function (Blueprint $table) {
        $table->increments('id');
        // other fields ...    
    });
}

应用程序

public function up()
{
    Schema::create('applications', function (Blueprint $table) {
        $table->increments('id');
        // other fields ...
        $table->integer('applicant_id')->unsigned();

        // other relations ...
        $table->foreign('applicant_id')->references('id')->on('applications')->onDelete('cascade');
    });
}

我只想创建一个新申请人,然后为刚刚创建的申请人添加一个新申请:

$applicant = Applicant::create([
    // data
]);

$application = $applicant->applications()->create([
    // data
]);

但是,当运行此代码时,我收到以下错误:

SQLSTATE[23000]: Integrity constraint violation: 
1452 Cannot add or update a child row: a foreign key constraint fails (
    `dbname`.`applications`, CONSTRAINT `applications_applicant_id_foreign` 
    FOREIGN KEY (`applicant_id`) REFERENCES `applications` (`id`) ON DELETE CASCADE
)
(SQL: insert into `applications` (
    `status`,
    `reference_number`,
    `organisation_id`,
    `qualification_id`,
    `applicant_id`,
    `updated_at`,
    `created_at`
) values (
    pending,
    573066CE59BFE,
    24,
    1,
    12, // <------ applicant_id, i.e. the foreign key!
    2016-05-09 11:30:38,
    2016-05-09 11:30:38
))

据我了解,发生错误是因为我向其传递了数据库中不存在的外键。所以我想知道我第一次调用数据库来创建申请人时发生了什么:

$applicant = Applicant::create([
    // data
]);

在创建应用程序的第二条语句之前是否没有写入数据库:

$application = $applicant->application()->create([
    // data
]);

...从而导致完整性约束违规?因为如果我在创建后立即 dd($applicant)dd(Applicant::find($applicant->id)) 我会获得记录,并且还可以查看它在数据库中。

我发现在重构代码之前,我调用 create() 来添加新记录,然后逐行构建新的应用程序并使用 save( ),我没有遇到这个问题。所以我很想知道这两个调用有何不同(如果有的话)以及处理这种情况的正确方法是什么,因为我认为这是非常简单的事情,我之前已经做过很多次了。任何建议将不胜感激,谢谢!

编辑 1

更正关系调用:

$applicant->application()->create(...)

不是:

$applicant->applications()->create(...)

编辑2

运行此代码:

$applicant = Applicant::create($this->applicantDataFromRequest($request));

$application = new Application([
    'status'           => 'pending',
    'reference_number' => $request->get('passport_number'),
    'organisation_id'  => $request->get('organisation'),
    'qualification_id' => $request->get('qualification') ?: null,
]);

$applicant->application()->save($application);

dd('done');

并收到相同的错误(已更新页面上的所有错误):

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`dbname`.`applications`, CONSTRAINT `applications_applicant_id_foreign` FOREIGN KEY (`applicant_id`) REFERENCES `applications` (`id`) ON DELETE CASCADE) (SQL: insert into `applications` (`status`, `reference_number`, `organisation_id`, `qualification_id`, `applicant_id`, `updated_at`, `created_at`) values (pending, 5730970933C7B, 24, 1, 22, 2016-05-09 14:56:25, 2016-05-09 14:56:25))

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`dbname`.`applications`, CONSTRAINT `applications_applicant_id_foreign` FOREIGN KEY (`applicant_id`) REFERENCES `applications` (`id`) ON DELETE CASCADE)

编辑3 添加了相关迁移

更新1

真奇怪!我已经通过 git 恢复到了该项目的旧版本,在我开始重构代码之前它可以正常工作,但现在由于同样的原因它不起作用了!不知道这里发生了什么!?

更新2

刚刚注意到迁移中有些非常愚蠢的事情:

应用程序

public function up()
{
    Schema::create('applications', function (Blueprint $table) {
        $table->increments('id');
        // other fields ...
        $table->integer('applicant_id')->unsigned();

        // other relations ...
        $table->foreign('applicant_id')->references('id')->on('applications')->onDelete('cascade');
    });
}

外键应该是:

$table->foreign('applicant_id')
    ->references('id')
    ->on('applicants')
    ->onDelete('cascade'); // not applications!

这里有两点:

  1. 为什么到现在为止这还没有影响我的代码?一直工作正常,直到现在有点奇怪......

  2. 将更新外键约束并尝试一下,看看现在是否有效

最佳答案

试试这个:

$applicant = new Applicant([
    // data
]);

$application = new Application([
    // data
]);

$applicant->applications()->save($application);

关于php - Laravel Eloquent 创建方法导致完整性约束违规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37114055/

相关文章:

php - 将数据保存到数据库时出错

mysql - 为什么此聚合查询返回的行比应有的少了一行?

mysql - Rails/mysql SUM 不同记录 - 优化

mysql - 问题白色 UPDATE 和 IF(选择)

php - 公理 : Network Error with Vuejs

php - Laravel 和 Eloquent - 应用不同的过滤器

sql - laravel查询生成器或内部

php - 我们可以在 php 的 foreach 循环中使用 IterateAggregate 或 Iterator 吗?

php - PHP 中有什么类似于 Ruby 中的中间人吗?

PHP mail() 函数服务器和本地主机不工作