需要在 Laravel 4 的同一张表中设置一对多的关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28930251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Need to set a 1 to many relationship in the same table in Laravel 4
提问by Bassem Aiad
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)
ErrorException (E_UNKNOWN) 未定义的属性:Illuminate\Database\Eloquent\Builder::$parent(视图:/var/www/phpWithAngulerJS/app/views/admin/category-edit.blade.php)
回答by Jarek Tkaczyk
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;