这是我的模特
//relation from model products to model categorys
public function categorys()
{
return $this->belongsTo('App\Category');
}
//relation from model products to model categorys
public function categorys()
{
return $this->belongsTo('App\Category');
}
这是我的控制器
public function index()
{
//controller buat manggil foreachnya
$data['title'] ='Product';
$data['page'] = 'Semua Product';
$data['products'] = Product::all();
return view('backend.product.index', $data);
}
**这是我的**
@foreach($products->categorys as $key => $value)
<tr>
<!-- view bladenya -->
<td>{{$key+1}}</td>
<td>{{$value->category_id->category}}</td>
<td>{{$value->product}}</td>
[我正在尝试使用$ products-> $ categorys,但它出了问题
首先,您需要对产品执行foreach循环,然后针对每个产品对类别进行foreach循环。意思是:
@foreach($data['products'] as $product)
...
@foreach($product->categories as $category)
//You have list of categories for each product here
@endforeach
...
@endforeach
您需要根据以下内容更改代码:
从模型categorys()
中删除重复的功能,并使用public function categories()
更改现有的功能名称>
在您的控制器中,如下更改您的行:
return view('backend.product.index')->with($data);
在刀片文件中,您可以按以下方式访问它:
@foreach($products->categories as $category)
// Now You can access categories for each product here
@endforeach