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

ぐ巨炮叔叔 提交于 2019-12-20 10:04:27

问题


I have the following models

Category:

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

Need to set a 1 to many relationship in the category table Ex category "cities" is a child of category "countries"

the error happen when i try to use the following code

<?php

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

?>

The error :

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


回答1:


First off, fix the relations as follows:

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

And your query needs to be executed first:

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

echo $parent->title;


来源:https://stackoverflow.com/questions/28930251/need-to-set-a-1-to-many-relationship-in-the-same-table-in-laravel-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!