需要在Laravel 4的同一个表中设置1对多的关系

时间:2015-03-08 18:29:34

标签: laravel laravel-4 eloquent foreign-key-relationship

我有以下型号

类别:

<?php

class Category extends Eloquent {
    protected $table = "category";
    protected $fillable = array('title','parent','metatit','metadsc','metake','metaurl','image');
    public function categoryitems(){
        return $this->hasMany('CategoryItem','catid');
    }
    public function parent(){
        return $this->hasMany('category','parent');
    }
    public function child(){
        return $this->belongsTo('Category','parent');
    }
}

需要在类别表中设置1对多的关系 Ex类别“城市”是“国家”类别的孩子

当我尝试使用以下代码时发生错误

<?php

$parent = Category::where('id','=',$cat->id)->parent;
echo $parent->title;

?>

错误:

  

ErrorException(E_UNKNOWN)   未定义的属性:Illuminate \ Database \ Eloquent \ Builder :: $ parent(查看:/var/www/phpWithAngulerJS/app/views/admin/category-edit.blade.php)

1 个答案:

答案 0 :(得分:12)

首先,按如下方式修复关系:

public function children() {
    return $this->hasMany('Category','parent');
}
public function parent() {
    return $this->belongsTo('Category','parent');
}

您的查询需要先执行:

$parent = Category::where('id','=',$cat->id)->first()->parent;
// btw since you have $cat, you probably can do simply:
$cat->parent;

echo $parent->title;