我有多个关系的类别和子类别表
class Category extends Model {
protected $table='categories';
protected $fillable=['name'];
public function subcategories() {
return $this->belongsToMany('App\Modules\Subcategory\Models\Subcategory', 'categories_subcategories', 'category_id', 'subcategory_id');
}
}
子类别
class Subcategory extends Model {
protected $table='subcategories';
protected $fillable=['name'];
public function categories()
{
return $this->belongsToMany('App\Modules\Category\Models\Category', 'categories_subcategories', 'subcategory_id', 'category_id');
}
}
控制器中的
public function catSubList()
{
$subcategories = Subcategory::with('categories')->get();
return view('Subcategory::category_subcategory',compact('subcategories'));
}
但是当我尝试使用以下视图访问数据时
@foreach($subcategories as $row)
<td>{{$i}}</td>
<td>{{$row->name}}</td>
<td>{{$row->categories->name}}</td>
@endforeach
我得到的错误如下:
Collection.php第1527行中的ErrorException:此集合实例上不存在Property [name]。
我如何访问$row->categories->name
?有意见的人吗?
答案 0 :(得分:1)
您必须创建另一个foreach()循环因为您的子类别属于ToMany类别。 row->categories
返回一个集合,而不是一个对象。因此错误。
<td>{{$row->name}}</td>
<td>{{$row->categories->name}}</td>
@foreach($row->categories as $category)
<td>{{$category->name}}</td>
@endforeach
<强>更新强>
获取包含所有子类别的类别。只需反转您的查询
$category = Category::with('subcategories')
->where('name', '=', 'cars')
->first();
//will return you the category 'cars' with all sub categories of 'cars'.
无需加载
$category = Category::find(1);
$subacategories = $category->subcategories;
return view('Subcategory::category_subcategory', compact('category', subcategories));