Search code examples
phplaravele-commerce

How to create a relationship within a table in laravel?


I need to create a relationship within a table. I attached my table below.

enter image description here

This is my Category model.

class Category extends Model
{
    public function products()
    {
       return $this->hasMany(Product::class);
    }

    public function categories_id() {
        return $this->hasMany('category_id','parent_id');
    }
    public function parent_id() {
        return $this->hasMany('category_id','parent_id');
    }
}

Here how can I relate category_id and parent_id?

This is my categories_table.

 public function up()
    {
       Schema::create('categories', function (Blueprint $table)
        {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('parent_id')->nullable();
        $table->string('cat_name')->nullable();
        $table->string('cat_image_path')->nullable();
        $table->timestamps();
         });
    }

Solution

  • You can try this setup:

    public function parent()
    {
        return $this->belongsTo(self::class);
        // uses `parent_id` to find the parent by 'id'
    }
    
    public function children()
    {
        return $this->hasMany(self::class, 'parent_id');
        // finds other records where their 'parent_id' is the parent's 'id'
    }
    
    $category = Category::find(...);
    
    $parent = $category->parent;
    $children = $category->children;
    

    Also, there is no category_id field in your schema.

    Everything you want to know about these relationships is in the documentation.

    Laravel 7.x Docs - Eloquent - Relationships - One To Many hasMany

    Laravel 7.x Docs - Eloquent - Relationships - One To Many (Inverse) belongsTo

    Laravel 7.x Docs - Eloquent - Relationships - Relationship Methods vs Dynamic Properties