Laravel外键约束错误求助:errno:150添加->unsigned()仍未解决
Hey there, let's work through this foreign key issue you're facing—adding ->unsigned() was a solid first move, but there are a few other easy-to-miss details that often cause this error to stick around. Here are the most common fixes to check:
Ensure Column Types Match Exactly
Your foreign key column and the primary key it references must be identical in type. For example:- If your parent table uses
bigIncrements('id')(which creates aBIGINTprimary key), your foreign key column needs to beunsignedBigInteger('user_id')—notunsignedInteger. Mismatched types likeINTvsBIGINTwill immediately trigger the 150 error.
Example of correct matching:
// Parent table (users) migration Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); // BIGINT primary key // Other fields... }); // Child table (posts) migration Schema::create('posts', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('user_id'); // Matches parent's BIGINT type $table->foreign('user_id')->references('id')->on('users'); });- If your parent table uses
Verify Migration Execution Order
The parent table must be created before any child tables that reference it. If your child table's migration file has an earlier timestamp in its filename,migrate:freshwill try to create the child table first—when the parent doesn't exist yet, the foreign key constraint fails.
Fix this by either:- Renaming the migration files to ensure the parent table's file has an earlier timestamp, or
- Running the parent migration manually first:
php artisan migrate --path=database/migrations/[parent-migration-filename].php
Confirm Your Tables Use InnoDB
MyISAM (another MySQL engine) doesn't support foreign key constraints. Laravel defaults to InnoDB, but if this was changed, explicitly set the engine in your migrations:Schema::create('posts', function (Blueprint $table) { $table->engine = 'InnoDB'; // Fields and foreign key setup... });Check for Nullable Constraints (If Applicable)
If your foreign key column should allowNULLvalues, add->nullable()to the column definition. Without this, if there's no default value or existing data doesn't match, you'll hit the error. Pair it with an appropriate on-delete action if needed:$table->unsignedBigInteger('user_id')->nullable(); $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');Double-Check Table/Column Spelling
Typos are sneaky! Make sure the table name inon('users')and column name inreferences('id')exactly match your actual tables and columns. A tiny typo likeuserinstead ofuserswill break the constraint.
Start with checking column types and migration order—those are the two most frequent culprits. If you still run into issues, sharing your migration code snippets would help narrow it down further!
内容的提问来源于stack exchange,提问作者Phuc Vo

