【发布时间】:2016-10-28 07:26:18
【问题描述】:
我有两个表,产品和子产品。 我还有一个显示产品信息的视图(查看从数据库动态生成的数据)。在此视图中,应显示所有子产品。我怎样才能做到这一点?因为我在视图中循环第一个查询,而不是在控制器中。
控制器:
public function showSpecificProduct($name)
{
$name = strtolower($name);
$product = \DB::select('select * from products where name = ? LIMIT 1', [$name]);
$subProducts = \DB::select('select * from subproducts where mainproduct = ?', [/* id from $product belongs here */]);
return view('products.single', ['products' => $product, 'subproducts' => $subProducts]);
}
查看:
@foreach ($products as $product)
<div class="col-md-4">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">{{ $product->name }}</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<img src="{{ $product->img }}" alt="{{ $product->name }}" class="img-responsive">
</div>
</div>
<!-- /.box -->
</div>
@endforeach
另外,有没有更好的方法在 laravel 中进行第一次查询?因为我使用的是 foreach 循环,而只有 1 行。
提前谢谢你
【问题讨论】: