How to create self referential relationship in laravel?

前端 未结 4 873
臣服心动
臣服心动 2020-12-02 18:03

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 pr

4条回答
  •  悲哀的现实
    2020-12-02 19:09

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

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

    EDIT

    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');
        }
    }
    

提交回复
热议问题