Bas*_*iad 7 foreign-key-relationship laravel eloquent 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');
}
}
Run Code Online (Sandbox Code Playgroud)
需要在类别表中设置1到多个关系Ex类别"cities"是类别"countries"的子项
当我尝试使用以下代码时发生错误
<?php
$parent = Category::where('id','=',$cat->id)->parent;
echo $parent->title;
?>
Run Code Online (Sandbox Code Playgroud)
错误 :
ErrorException(E_UNKNOWN)未定义属性:Illuminate\Database\Eloquent\Builder :: $ parent(查看:/var/www/phpWithAngulerJS/app/views/admin/category-edit.blade.php)
Jar*_*zyk 14
首先,修复关系如下:
public function children() {
return $this->hasMany('Category','parent');
}
public function parent() {
return $this->belongsTo('Category','parent');
}
Run Code Online (Sandbox Code Playgroud)
您的查询需要先执行:
$parent = Category::where('id','=',$cat->id)->first()->parent;
// btw since you have $cat, you probably can do simply:
$cat->parent;
echo $parent->title;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5900 次 |
| 最近记录: |