问题
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
, CONSTRAINTexternal_id_foreign
FOREIGN KEY (id
) REFERENCESorder
(order_id
)) (SQL: insert intoexternal
(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