我有两个表,一个表用于存储有关名为 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/