php - 如何在 laravel 5.6 中使用 hasMany 分页并显示所有记录?

标签 php mysql laravel eloquent

我有两个表,一个表用于存储有关名为 orders 的订单的一般信息,另一个表用于存储产品、备注和交货日期等信息。

基本上,我想在同一页面中显示表格订单,每个订单可以是表格详细信息中的多个产品、注释、日期,而且我想分页以便在每个页面上准确显示 20 个订单,每个产品、注释、日期行都具有相同的 id_order。

总而言之,每一页上都有 20 个订单表中的订单,但表详细信息中可以有 40 行,其中包含产品、备注、交货日期,因为一个订单可以包含多个产品。事实上,我想使用 rowspan html 以便在同一行上显示详细信息。

这是我的订单模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class order extends Model
{
    public $timestamps = false;

    protected $fillable = ['client','number_order','file'];

    public function details()
    {
        return $this->hasMany('App\Detail','orders_id')->orderBy('id', 'desc');
    }
}

详细模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Detail extends Model
{
    protected $table = 'detail';

    public function order()
    {
        return $this->belongsTo('Detail','orders_id');
    }
}

我的 Controller :

public function index()
{
    $orders = Order::first(); //This works only with one record I cant show all records, all() is not working

    $orders->setRelation('details', $orders->details()->paginate(10));

    return view('orders.index', compact('orders'));
}

查看:

<tbody>
    @foreach ($orders->details as $detail)
        <tr id="{{ $detail->orders_id }}">
            <td>{{ $detail->product }}</td>
        </tr>
    @endforeach
</tbody>

最佳答案

您可以像这样在订单上使用预先加载详细信息

public function index()
{
    $orders = Order::with('details')->paginate(20);
    return view('orders.index', compact('orders'));
}

在 View 中

<table>
    <tbody>
      @foreach($orders as $order)
        <tr>
            <td>{{ $order->created_at }}</td>
            <td>... put any order info here</td>
            <td>
                <label>Order Details:</label>
                <table>
                    @foreach ($order->details as $detail)
                        <tr id="{{ $detail->orders_id }}">
                            <td>{{ $detail->product }}</td>
                            <td>{{ $detail->note }}</td>
                        </tr>
                    @endforeach
                </table>
            <td>
        </tr>
      @endforeach
    </tbody>
</table>

关于php - 如何在 laravel 5.6 中使用 hasMany 分页并显示所有记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51567488/

相关文章:

php - Docker 默认情况下不提供服务

php - 每 30 分钟自动删除 FTP 文件夹中的所有文件

php - 如何将字符串与选项值进行比较

MySQL:将表连接到自身

php - Cookie::忘记不工作 laravel 5.1

php - 使用php检测并输出特定程序是否正在运行

php - pg_free_result() 是否必要,即使结果超出范围?

php - 如何在 php laravel 内迁移转储数据库 (users.sql)?

php - 如何一次插入多个技能?

php - 在不使用付费服务作为 Pusher 的情况下创建 Laravel 广播的最简单方法是什么?