如何在Laravel中建立自我参照关系? [英] How to create self referential relationship in laravel?
本文介绍了如何在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 {
function posts(){
return $this->hasMany('Post', 'parent_id');
}
}
编辑
尝试这种构造
class Post extends Eloquent {
public function parent()
{
return $this->belongsTo('Post', 'parent_id');
}
public function children()
{
return $this->hasMany('Post', 'parent_id');
}
}
这篇关于如何在Laravel中建立自我参照关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文