cd7uvq
Last Updated: February 25, 2016
·
15.22K
· maumagau

Laravel parent/child relationship

Create a parent/child relationship within a model, based on a parent_id in the databast table

id name    parent_id
1 Group 1  NULL
2 Group 2  1
<?php // model

class Group extends Eloquent {

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

    public function children()
    {
        return $this->hasMany('group', 'parent_id');
    }
}
// Controller
$group = $this->group->with('children', 'parent')->find(1);
// Outputs:
/*
array (size=8)
  'id' => int 1
  'name' => string 'Group 1' (length=7)
  'parent_id' => null
  'children' => 
    array (size=1)
      0 => 
        array (size=5)
          'id' => int 2
          'name' => string 'Group 2' (length=7)
          'parent_id' => int 1
  'parent' => null
*/

2 Responses
Add your response

17132

Hello!

I have a similar code with parent and children elements.
But I dont know to make to save a parent when save a group.

Can you help me?

over 1 year ago ·
17839

What about Nested Set Model?

over 1 year ago ·