我是Laravel的新手.我只想创建一个自引用模型.例如,我想创建一个产品类别,其中该字段parent_id与产品类别ID相同.这怎么可能?
型号如下所示
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');
}
}
Run Code Online (Sandbox Code Playgroud)
结果达到了'100'的最大功能嵌套级别,正在中止!错误
Jac*_*int 60
您可以向模型添加关系,并为关系字段设置自定义键.
class Post extends Eloquent {
function posts(){
return $this->hasMany('Post', 'parent_id');
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
尝试这种结构
class Post extends Eloquent {
public function parent()
{
return $this->belongsTo('Post', 'parent_id');
}
public function children()
{
return $this->hasMany('Post', 'parent_id');
}
}
Run Code Online (Sandbox Code Playgroud)
您的模型没有因为产生"达到'100'的最大函数嵌套级别"错误而出错.这是XDebug的配置; 增加你的xdebug.max_nesting_level.
以下是@sitesense在laracasts.com上的2015年帖子:
这不是Laravel,Symfony或其他任何内容的错误.它仅在安装XDebug时发生.
它只是因为递归调用100个或更多函数而发生.这不是一个很高的数字,XDebug(> = 2.3.0)的更高版本已将此限制提高到256.请参见此处:
http://bugs.xdebug.org/bug_view_page.php?bug_id=00001100
编辑:事实上,最新的Homestead配置脚本已经将限制设置为250.请参见第122行:
https://github.com/laravel/settler/blob/master/scripts/provision.sh#L122
所以添加xdebug.max_nesting_level = 250到php.ini应该这样做.
根据您尝试访问父级的评论,我在代码中添加了更多内容!
class Person extends \Eloquent {
protected $fillable = [];
var $mom, $kids;
function __construct() {
if($this->dependency_id<>0) {
$this->mother->with('mother');
}
}
public function children() {
$children = $this->hasMany('Person','dependency_id');
foreach($children as $child) {
$child->mom = $this;
}
return $children;
}
public function mother() {
$mother = $this->belongsTo('Person','dependency_id');
if(isset($mother->kids)) {
$mother->kids->merge($mother);
}
return $mother;
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以通过急切加载从孩子访问父母,在此处查看更多信息:http : //neonos.net/laravel-eloquent-model-parentchild-relationship-with-itself/