如何在 laravel 中创建自引用关系? [英] How to create self referential relationship in laravel?

查看:15
本文介绍了如何在 laravel 中创建自引用关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Laravel 的新手.我只想创建一个自引用模型.例如,我想创建一个产品类别,其中 parent_id 字段与产品类别 ID 相同.这怎么可能?

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?

型号如下所示

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

结果达到了100"的最大函数嵌套级别,正在中止!错误

It results Maximum function nesting level of '100' reached, aborting! Error

推荐答案

可以为模型添加关系,并为关系字段设置自定义键.

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

更新:

试试这个结构

class Post extends Eloquent {

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

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

旧答案:

class Post extends Eloquent {

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

这篇关于如何在 laravel 中创建自引用关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆