Laravel Eloquent Self Join Parent Child

2019-09-11 03:34发布

Laravel Eloquent Self Join Parent Child Relationship

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

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.

1条回答
Fickle 薄情
2楼-- · 2019-09-11 04:11

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');
}
查看更多
登录 后发表回答