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

Need to set a 1 to many relationship in the same table in Laravel 4

我有以下型号

类别:

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

需要在类别中设置一对多的关系table 例如类别 "cities" 是类别 "countries"

的子类别

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

<?php

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

?>

错误:

ErrorException (E_UNKNOWN) Undefined property: Illuminate\Database\Eloquent\Builder::$parent (View: /var/www/phpWithAngulerJS/app/views/admin/category-edit.blade.php)

首先,确定关系如下:

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;