我是 Laravel 11 的新手,我一直被这个问题困扰(erno: 150“外键约束格式不正确”),尽管尝试了我见过的各种建议,但我仍然无法解决它。您能帮我找出哪里出了问题以及如何解决吗?
这是费用表
public function up(): void
{
Schema::create('expenses', function (Blueprint $table) {
$table->id();
$table->increments('category_id');
$table->foreign('category_id')->references('id')
->on(table:'categories')->onDelete('cascade')->onUpdate(action:'cascade');
$table->decimal('amount',8, 2);
$table->date('entry_date');
$table->timestamps();
$table->engine = 'InnoDB';
});
}
这是类别表
public function up(): void
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category_name');
$table->string('description')->nullable();
$table->timestamps();
});
}
我需要将费用表中的外键category_id连接到类别表。当我更新一个类别时,我希望费用表中的category_id也更新,删除也是如此。如果删除了特定的category_name,我希望费用表中的相应记录也被删除。
您在费用表中声明的category_id列不能递增。您必须定义以下内容,
public function up(): void
{
Schema::create('expenses', function (Blueprint $table) {
$table->id(); // Primary key for the expenses table
$table->unsignedBigInteger('category_id'); // Set up the foreign key constraint
$table->decimal('amount', 8, 2);
$table->date('entry_date');
$table->timestamps();
$table->engine = 'InnoDB';
$table->foreign('category_id') // Foreign key reference to the categories table
->references('id')
->on('categories')
->onDelete('cascade')
->onUpdate('cascade');
});
}