How to create self referential relationship in laravel?

laravel-4

Solution

You can add a relation to the model and set the custom key for the relation field.

Update:

Try this construction

class Post extends Eloquent {

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

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

Old answer:

class Post extends Eloquent {

    function posts(){
        return $this->hasMany('Post', 'parent_id');
    }
}

Problem

I am new to Laravel. I Just want to create a self referential model. For example, I want to create a product category in which the field `parent_id` as same as product category id. How is this possible? Model Shown below ``` class Product_category extends Eloquent { protected $guarded = array(); public static $rules = array( 'name' => 'required', 'parent_id' => 'required' ); function product_category() { return $this->belongsto('Product_category','parent_id'); } } ``` It results Maximum function nesting level of '100' reached, aborting! Error

Original source