V
V
Vova1357982022-03-08 08:31:16
Laravel
Vova135798, 2022-03-08 08:31:16

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

2 answer(s)
S
Sergey, 2022-03-08
@KingstonKMS

The field types in the relationship must be the same. And your error is not about communication at all

I
Igor, 2022-03-17
@ig0r74

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();
});

In the model:
public function children(): HasMany
{
    return $this->hasMany(Category::class, 'parent_id');
}

public function parent(): BelongsTo
{
    return $this->belongsTo(Category::class, 'parent_id');
}

You can use static::class instead of Category:: class

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question