Answer the question
In order to leave comments, you need to log in
How to make the model relate to itself?
I want to make multiple category levels. How can I do it? I tried to do it but it gives me an error
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'categories' already exists (SQL: create table `categories` (`id` bigint unsigned not null auto_increment primary key, `title` varchar(255) not null, `slug` varchar(255) null, `parent_id` bigint unsigned not null default '0', `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug')->unique()->nullable();
$table->unsignedBigInteger('parent_id')->default(0);
$table->timestamps();
$table->foreign('parent_id')->references('id')->on('categories')->onDelete('CASCADE');
});
}
Answer the question
In order to leave comments, you need to log in
The field types in the relationship must be the same. And your error is not about communication at all
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->foreignId('parent_id')->nullable()->constrained('categories')->cascadeOnDelete();
$table->string('name');
$table->mediumText('description')->nullable();
$table->unsignedInteger('rank')->default(0);
$table->boolean('active')->default(0);
$table->timestamps();
});
public function children(): HasMany
{
return $this->hasMany(Category::class, 'parent_id');
}
public function parent(): BelongsTo
{
return $this->belongsTo(Category::class, 'parent_id');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question