SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row (Laravel 6)

纵饮孤独 提交于 2021-01-28 08:02:20

问题


What am I doing wrong?

Environment: Laravel 6, Homestead (Local), Windows 10

Create External Table (Migration):

Schema::create('external', function (Blueprint $table) {
                $table->increments('id')->unsigned();
                $table->foreign('id')->references('order_id')->on('order');
            });

Create Order Table (Migration):

Schema::create('order', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('order_id')->index();

External.php (model):

class External extends Model
    public function orders()
    {
        return $this->hasMany(Order::class);
    }
}

Order.php (Model):

public function external()
{
    return $this->belongsTo(External::class);
}

Error Message:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (homestead.external, CONSTRAINT external_id_foreign FOREIGN KEY (id) REFERENCES order (order_id)) (SQL: insert into external (site_order_id, order_status,...


回答1:


The error is a common one, and easy to explain. Your Laravel code is generating one (or more) insert which is referring to a record in the order table which does not exist. Try running the following query:

SELECT o.*
FROM [order] o
WHERE order_id = <external.id value here>

If you get back an empty result set, then it means your insert is referring to data in order which does not exist.




回答2:


Edited (External Table Migration):

$table->unsignedBigInteger('id')->nullable();
$table->foreign('id')->references('order_id')->on('order');

Edited (Order Table Migration):

$table->increments('id');
$table->unsignedBigInteger('order_id')->index()->unsigned();


来源:https://stackoverflow.com/questions/58056073/sqlstate23000-integrity-constraint-violation-1452-cannot-add-or-update-a-chi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!