【发布时间】:2015-06-18 05:31:22
【问题描述】:
我正在使用 Laravel 创建一个 CRUD 应用程序,但我有点卡住了。我想要做的是为“产品”表中的每个产品显示“类别”表中的对应类别。我试图在一个视图中压缩这两个表并在@foreach 中创建一个@foreach,但它只列出了所有类别,而不是根据 products 表中的 category_id 分配对应的类别。
控制器
$products = products::all();
$categories = categories::all();
return View::make('products.index')->with('products', $products)->with('categories', $categories);
查看
@foreach($products as $key => $value)
<tr>
<td>{!! $value->id !!}</td>
<td>{!! $value->product_name !!}</td>
@foreach($categories as $key2 => $value2)
<td>{!! $value2->category !!}</td>
@endforeach
<td>{!! $value->product_price !!}</td>
<td>{!! $value->updated_at !!}</td>
<td>
@endforeach
产品表
Schema::create('products', function($table)
{
$table->increments('id');
$table->integer('category_id')->unsigned()->nullable();
$table->string('product_name', 255)->unique();
$table->decimal('product_price', 10, 4);
$table->dateTime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));
});
Schema::table('products', function($table) {
$table->foreign('category_id')->references('id')->on('categories');
});
分类表
Schema::create('categories', function($table)
{
$table->increments('id');
$table->string('category', 255)->unique();
$table->dateTime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));
});
【问题讨论】:
-
当您执行
$products = products::all();和$categories = categories::all();时,不会自动关联这两个结果集合。这就是为什么您从内部循环中获取整个类别列表的原因。 -
Laravel 有没有办法将每个产品关联到对应的类别?我搜索了答案和内容,并通过创建数据透视表找到了解决方案。但我认为也许有更简单的方法来做到这一点。
-
是的,我认为有一个更简单的方法。首先,一个产品可能有多个类别,还是只有一个?
-
每个产品只有一个类别。