SQLSTATE[HY000]: General error: 1005 Can't create table
laravel
.projects
(errno: 150 "Foreign key constraint is incorrectly formed")
I get the above error when I migrate my projects table and try to join three tables which:
- A user has many products, and products have their own id.
- A product has many projects, and projects have their own id.
User table (user.php)
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->text('profile_photo_path')->nullable();
$table->timestamps();
});
}
Product table (product.php)
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('detail');
$table->string('color');
$table->string('image');
$table->string('logo');
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
Project table (project.php)
Schema::create('projects', function (Blueprint $table) {
// $table->('id');
$table->bigIncrements('id');
$table->string('name', 255)->nullable();
$table->string('detail', 500)->nullable();
$table->string('color', 255)->nullable();
$table->string('image', 22)->nullable();
$table->string('logo', 22)->nullable();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('product_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable();
});
User model
public function getProducts()
{
return $this->hasMany('App\Models\Product');
}
public function getProject()
{
return $this->hasMany('App\Models\Project');
}
Product model
use HasFactory;
protected $fillable = [
'name', 'detail', 'image', 'color', 'logo', 'user_id'
];
public function getUser()
{
return $this->belongsTo(User::class);
}
Project model
use HasFactory;
protected $fillable = [
'name', 'detail', 'image','color','logo','user_id'
];
public function getUser(){
return $this->belongsTo(User::class);
}
I also need help to make my model work.