需要在Laravel 4的同一张表中设置1对多的关系 [英] Need to set a 1 to many relationship in the same table in Laravel 4

查看:105
本文介绍了需要在Laravel 4的同一张表中设置1对多的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号

类别:

<?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对多的关系 前城市"类别是国家"类别的子代

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;

?>

错误:

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

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

推荐答案

首先,按如下所示解决关系:

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;

这篇关于需要在Laravel 4的同一张表中设置1对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆