Laravel Eloquent Self Join Parent Child

不问归期 提交于 2019-12-12 03:49:30

问题


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


来源:https://stackoverflow.com/questions/37500527/laravel-eloquent-self-join-parent-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!