#I am facing problem , can't migrate Product table

21 messages · Page 1 of 1 (latest)

maiden spire
#
class Product extends Model
{
    use HasFactory;
    protected $primaryKey = "p_Id";
    public function category()
    {
        return $this->belongsTo(App\Models\Category::class, 'C_Id');
    }
}

class Category extends Model
{
    use HasFactory;

    protected $primaryKey = "C_ID";
    public function products()
    {
        return $this->hasMany(App\Models\Product::class, 'C_ID');
    }
}
        Schema::create('products', function (Blueprint $table) {
            $table->id('p_Id');
            $table->foreignId('C_ID')->constrained('categories');
            $table->string('Title');
            $table->text('Description');
            $table->string('Image');
            $table->decimal('Price', 10, 2);
            $table->decimal('Sale', 10, 2)->nullable();

            $table->timestamps();
        });
    }

wheat zealot
#

Are you getting any errors?

maiden spire
#

SQLSTATE[HY000]: General error: 1005 Can't create table myblog.products (errno: 150 "Foreign key constraint is incorrectly formed") (Connection: mysql, SQL: alter table products add constraint products_c_id_foreign foreign key (C_ID) references categories (id))

quasi nest
#

The casing of them is all over the place so no wonder you’re getting errors.

maiden spire
#

I am newbie student

quasi nest
wheat zealot
#

The foreignId() type assumes you're using conventional names for your keys. if you're not following conventions, you'll have to manually create the column and foreign key constraint

maiden spire
#

i am sorry i never heard about conventional names

wheat zealot
quasi nest
maiden spire
quasi nest
#

Just use $table->id() and it will create a column named id

maiden spire
#

of design

quasi nest
#

There’s nothing “normalising” about using “C_ID” over id as the name of a primary key column.

#

Laravel has conventions. Learn them.