本文介绍了Laravel雄辩的自我加入父母子女的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Product_category extends Model
{
    //
    protected $table='PRODUCT_CATEGORIES';
    public $timestamps = false;


    public function getParentCategory() {
        return $this->hasOne(self::class, 'id', 'parent_id');
    }.


    public function getChildCategories(){
        return $this->hasMany(self::class, 'parent_id','id');
    }

我能够通过使用getChildeCategories来检索表的所有子记录,但无法检索特定类别的Parent.它总是给我空值.

I am able to retrieve all child records of table by making use of getChildeCategories but not able to retrieve Parent of particular category.It always gives me null.

推荐答案

这称为一对多关系,hasMany关系的逆是belongsTo方法,您的getParentCategory()应为:

It's called one-to-many relationship, the inverse of a hasMany relationship is belongsTo method, your getParentCategory() should be:

public function getParentCategory() {
    return $this->belongsTo(self::class, 'parent_id');
}

public function getChildCategories(){
    return $this->hasMany(self::class, 'parent_id');
}

这篇关于Laravel雄辩的自我加入父母子女的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 07:58
查看更多