【问题标题】:Laravel 5 Pass data from two tables to the viewLaravel 5 将数据从两个表传递到视图
【发布时间】: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 有没有办法将每个产品关联到对应的类别?我搜索了答案和内容,并通过创建数据透视表找到了解决方案。但我认为也许有更简单的方法来做到这一点。
  • 是的,我认为有一个更简单的方法。首先,一个产品可能有多个类别,还是只有一个?
  • 每个产品只有一个类别。

标签: php laravel-5


【解决方案1】:

您可以使用join 在一个查询中获取每个产品的类别。

$products = DB::table('products')
    ->join('categories', 'products.category_id', '=', 'categories.id')->get();

如果每个产品只有一个类别,那么您的视图可以简化。

@foreach($products as $key => $value)
    <tr>
        <td>{!! $value->id !!}</td>
        <td>{!! $value->product_name !!}</td>
        <td>{!! $value->category !!}</td>
        <td>{!! $value->product_price !!}</td>
        <td>{!! $value->updated_at !!}</td>
    </tr>
@endforeach

【讨论】:

  • 它工作正常。我从没想过使用连接表。我应该更多地研究连接。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 1970-01-01
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
相关资源
最近更新 更多