Reputation: 23
I have two tables categories and subcategories and I want to show the category with their connected subcategories. For this I have created a query. It shows an error when I try to fetch a category name from a category table using one to many relationships.
The tables are structured as
categories; id, name
subcategories: id, category_id, subname
// Category.php model
class Category extends Model
{
protected $primaryKey = 'id';
protected $table = "categories";
public function subcategories()
{
return $this->hasMany('App\SubCategory');
}
}
// Subcategory.php model
class SubCategory extends Model
{
protected $primaryKey = 'id';
protected $table = "subcategories";
public function category()
{
return $this->hasMany('App\Category');
}
}
// Category Controller
public function show()
{
$categories= Category::all();
$subcategories=Subcategory::all();
return view('show',compact('categories','subcategories'));
}
// show.blade.php
@foreach($subcategories as $subcategory)
{{ $subcategory->subname }}
{{ $subcategory->category_id }}
{{ $subcategory->category->name }}
@endforeach
This line is giving me error {{ $subcategory->category->name }}
.
Upvotes: 2
Views: 734
Reputation: 1389
i need to change hasmany to belongsTo
You are right because subcategory has only one category and you need use belongsTo
relationship
class SubCategory extends Model
{
protected $primaryKey = 'id';
protected $table = "subcategories";
public function category()
{
return $this->belongsTo('App\Category');
}
}
Upvotes: 1