arsh's avatar
Level 1

Self Join In Eloquent Model

Hi guys, i am stuck in functionality of building functionality like self Join, for example i may have categories and nested categories, in categories table i put parent_id column which referes to same table but id column to perform categories hierarchy. I tried using hasOne and belongsTo relationship methods but its showing weird messages. i also tried belongsToMany method with same table with foreignkey,local key but then i am getting table alias error. i would really appriciate your help.

Regard.

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104
// Category.php

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

public function parent()
{
    return $this->belongsTo(Category::class, 'parent_id');
}
$category->children; // sub-categories collection

$category->parent; // parent instance
1 like
Joucke's avatar

Can you give us an example of said "weird messages"?

I'd say

public function parent_category()
{
    return $this->belongsTo(static::class, 'parent_id');
}

should do the trick, off the top of my head.

Please or to participate in this conversation.