Laravel:如何访问多对多关系数据

时间:2017-03-16 03:20:26

标签: php laravel laravel-5 eloquent

我有多个关系的类别和子类别表

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?有意见的人吗?

1 个答案:

答案 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));