Laravel Eloquent 如何获得第二或第三记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30551440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:40:30  来源:igfitidea点击:

Laravel Eloquent how to get the second or third record?

laraveleloquent

提问by nadir

I have an Order and a Product models.
"Order"HasMany Product (and Product belongsTo Order)...

我有一个订单和一个产品模型。
"Order"HasMany 产品(和产品属于订单)...

Let's say I want to display the 3 products of my order, how to do that ?
I know the first could be retrieved like $order->products->first()... but how to retrieve the second and third product?

假设我想显示我订单的 3 个产品,该怎么做?
我知道第一个可以像$order->products->first()……那样检索,但是如何检索第二个和第三个产品?

I tried $order->products->find(1)but "1" represents the id of the product... which I don't want to know...

我试过了,$order->products->find(1)但“1”代表产品的 id ......我不想知道......

回答by Luca C.

$order->products()->skip(1)->first();//Second row
$order->products()->skip(2)->first();//Third row
....

Is more performant than loading all products and getting only first, second, ecc..

比加载所有产品并仅获得第一、第二、ecc 的性能更高。



Instead if you want both second and third, you can get only them in a single query without load other rows, with similar approach:

相反,如果您同时需要 second 和third,您可以使用类似的方法在单个查询中仅获取它们而无需加载其他行:

$order->products()->skip(1)->take(2)->get(); //Skip first, take second and third

回答by nadir

I finally found the solution, this is the correct syntax:

我终于找到了解决方案,这是正确的语法:

 $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 

And so on...

等等...

回答by kupendra

You can simply try this :

你可以简单地试试这个:

$order->products->take(3)->get();

回答by Yevgeniy Afanasyev

Say you want a second product from Eloquent Collection

假设你想要第二个产品 Eloquent Collection

if you are sure that the array keys are same as array indexes, do that

如果您确定数组键与数组索引相同,请执行此操作

$order->products->get(1)->name;

if you need the second item and you are not sure about the array keys, do this

如果您需要第二项并且您不确定数组键,请执行此操作

$order->products->slice(1, 1)->first()->name;

回答by Anas

$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