mercredi 2 septembre 2015

laravel hasMany relationship not working as expected

I have two models called category and sub-category

Category.php

class Category extends Model
{
    protected $table = 'category';

    public $timestamps = false;

    public function subCategory(){

        return $this->hasMany('App\Subcategory', 'category_id');
    }
}

Subcategory.php

class Subcategory extends Model
{
    protected $table = 'subcategory';

    public $timestamps = false;

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

and I have foreign key column called category_id in my subcategory table in database

this is how I am trying to get all the subcategories for the selected category in my controller

$subcategory = Category::all();

and my blade view

 <ul>
            @foreach($categories as $categories)
            <li class='has-sub'><a href='#'>{{ $categories->category_name }}</a>
                <ul>
                    @foreach($subcategory->subCategory() as $sub)
                        <li><a href='#'>{{ $sub->subcategory_name }}</a></li>
                    @endforeach
                </ul>
            </li>
            @endforeach

        </ul>

I am able to get all the categories name for now but I can't get the name of sub-categories for the category..What I am missing here?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1VvHICG
via IFTTT

Aucun commentaire:

Enregistrer un commentaire