i'm Trying to migrate but it fails with this error and i've changed the format of the album_id/image_id to both integer and it keep giving this error
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1005 Can't create table `moses_photography`.`images` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `images` add constraint `images_album_id_foreign` foreign key (`album_id`) references `albums` (`image_id`))
at C:\xampp\htdocs\moses_photography\vendor\laravel\framework\src\Illuminate\Database\Connection.php:716
712▕ // If an exception occurs when attempting to run a query, we'll format the error
713▕ // message to include the bindings with SQL, which will make this exception a
714▕ // lot more helpful to the developer instead of just the database's errors.
715▕ catch (Exception $e) {
➜ 716▕ throw new QueryException(
717▕ $query, $this->prepareBindings($bindings), $e
718▕ );
719▕ }
720▕ }
1 C:\xampp\htdocs\moses_photography\vendor\laravel\framework\src\Illuminate\Database\Connection.php:501
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `moses_photography`.`images` (errno: 150 "Foreign key constraint is incorrectly formed")")
2 C:\xampp\htdocs\moses_photography\vendor\laravel\framework\src\Illuminate\Database\Connection.php:501
PDOStatement::execute()
albums table migration
*/
public function up()
{
Schema::create('albums', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('category_id');
$table->integer('image_id');
$table->timestamps();
});
}
images table migration
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->integer('album_id')->unsigned();
$table->foreign('album_id')->references('image_id')->on('albums');
$table->string('filename');
$table->timestamps();
});
CodePudding user response:
In SQL
the foreign key, needs to have the same type as the referenced id. Laravel migrations method ->id()
, is not an unsignedInteger()
but an unsignedBigInteger()
. So the following changes should help you.
$table->unsignedBigInteger('album_id');
$table->foreign('album_id')->references('image_id')->on('albums');