我有订单和产品型号
"Order"
HasMany产品(和产品属于订单)......
假设我要显示订单的3个产品,怎么做?
我知道第一个可以检索$order->products->first()
...但是如何检索第二个和第三个产品?
我试过$order->products->find(1)
但是“1”代表产品的ID ...我不想知道......
答案 0 :(得分:29)
我终于找到了解决方案,这是正确的语法:
$order->products->get(0)->name; will return the first record
$order->products->get(1)->name; will return the second record
$order->products->get(2)->name; will return the third record
等等......
答案 1 :(得分:27)
$order->products()->skip(1)->first();//Second row
$order->products()->skip(2)->first();//Third row
....
比装载所有产品更有效率,只获得第一,第二,ecc ..
答案 2 :(得分:1)
你可以试试这个:
$order->products->take(3)->get();
答案 3 :(得分:1)
说您想从Eloquent Collection
购买第二个产品
如果您确定数组键与数组索引相同,请执行
$order->products->get(1)->name;
如果您需要第二项并且不确定数组键,请执行此操作
$order->products->slice(1, 1)->first()->name;
答案 4 :(得分:1)
$order->products()->skip(1)->take(1)->first(); //Second row
$order->products()->skip(2)->take(1)->first(); //Third row
$order->products()->orderBy('salary','desc')->skip(1)->take(1)->first(); //Second highest salary row
$order->products()->orderBy('salary','desc')->skip(2)->take(1)->first(); //Third highest salary row