Laravel 5 create Table and Self-Referenced model (self Referencing)

2

How do I create a table autor referenced and how do I do the relationship in the same model?:

Example:

Tengo una tabla: Categoria
Campos: categoria_id, nombre, categoria_padre

It translates that a category (parent) can have many sub-categories (daughters) making the reference in the field category_father

    
asked by Rioyi Kaji 16.02.2018 в 05:35
source

2 answers

1

It really is very simple in Laravel, you simply define the relationships in the same model, with their respective foreign key:

public function hijas()
{
    return $this->hasMany('Categoria', 'categoria_padre');
}

public function padre()
{
    return $this->belongsTo('Categoria', 'categoria_padre');
}
    
answered by 16.02.2018 в 05:53
0

Yes, it's simple and for more advanced operations I recommend the package Baum , you can get all the descendants of a node in one only consultation, no matter how deep the tree.

class Catalog extends Node
{
    protected $fillable = [
        'name',
        'parent_id',
        'left',
        'right',
        'depth'
    ];
}

and already includes the relationships you need:

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

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

among others:

ancestorsAndSelf()
ancestors()
siblingsAndSelf()
siblings()
leaves()
descendantsAndSelf()
descendants()
immediateDescendants()
    
answered by 16.02.2018 в 14:31