Laravel Eloquent Self Join Parent Child

2019-09-11 03:38发布

问题:

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:

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