vendredi 30 octobre 2015

Laravel 5 Eloquent: Foreign key to same table belongsTo() not working

I have a "categories" table. A category can have many sub-categories The schema is ,

    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('category_id')->unsigned();
        $table->string('image');
        $table->timestamps();

        $table->foreign('category_id')->references('id')->on('categories');
    });  

And the relationship inside model class looks like,

public function child()
{
    return $this->hasMany('App\Category');
}

public function parent()
{
    return $this->belongsTo('App\Category');
}  

Now the child() method is working fine, But the parent() method is returning null.
So, $category->parent returns null



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire