【问题标题】:SQLSTATE[23000]: Integrity constraint violation in LaravelSQLSTATE[23000]:Laravel 中的完整性约束违规
【发布时间】:2017-10-08 06:05:53
【问题描述】:

当我单击提交(保存)按钮进行作业时...然后出现以下异常...(user_name 字段已在 job.create 中设置为隐藏。刀片查看表单)

您能告诉我在哪里可以修改以进行修复吗? 谢谢。

(3/3) 查询异常

SQLSTATE[23000]:违反完整性约束:1452 无法添加或 更新子行:外键约束失败(admin-db.jobs, 约束 jobs_customer_name_foreign 外键 (customer_name) 参考customers (customer_name)) (SQL: 插入jobs (user_name, customer_name, job_place, job_type, note_1, time_used, updated_at, created_at) 值 (John, 1, Kontor, Domene og Webhotell, asdf, , 2017-10-08 00:23:40, 2017-10-08 00:23:40))

timestamp_create_users_table.php

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->engine = 'InnoDB';            
        $table->increments('id')->unsigned();

        $table->string('name')->index();
        $table->string('email');
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

timestamp_create_customers_table.php

public function up()
{        
    Schema::create('customers', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->integer('id')->unsigned();

        $table->string('customer_name')->index();
        $table->string('customer_email');
        $table->timestamps();
        $table->softDeletes();
    });
}

timestamp_create_jobs_table.php

public function up()
{

    Schema::create('jobs', function (Blueprint $table) {
        $table->engine = 'InnoDB';

        $table->increments('id')->unsigned();

        $table->string('user_name')->index();
        $table->string('customer_name')->index();        
        $table->string('job_place');
        $table->string('job_type');
        $table->string('note_1');
        $table->time('time_used')->nullable();
        $table->timestamps();
        $table->softDeletes();

        $table->foreign('user_name')->nullable()->references('name')->on('users')->onDelete('cascade');
        $table->foreign('customer_name')->nullable()->references('customer_name')->on('customers')->onDelete('cascade');
    });
}

模型关系定义在:Job.php

public function users()
{
    return $this->belongsTo(User::class);
}

public function customers()
{
    return $this->belongsTo(Customer::class);
}

模型关系定义在:Customer.php

public function jobs()
{
    return $this->hasMany(Job::class);
}

【问题讨论】:

    标签: mysql exception laravel-5


    【解决方案1】:

    我自己得到了答案……

    问题在于使用 pluck 方法。 修改后,下面运行良好。

    <div class="form-group col-sm-6">
            {!! Form::label('customer_name', 'Customer Name:') !!}
            {!! Form::select('customer_name', $searchdata->pluck('customer_name', 'customer_name')->all(), null, ['class' => 'form-control']) !!}
    </div>
    

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 2020-01-31
      • 2021-03-22
      • 2017-09-11
      • 1970-01-01
      • 2021-08-26
      • 2020-01-28
      • 2015-07-17
      • 2021-07-23
      相关资源
      最近更新 更多