开发者

kohana find the second element of a collection (using find())

i have a kohana website and i have a situation where i always need to ge开发者_运维问答t the first two elements of a collection (they are actually pictures).

i take the first element very simple using :

     $image = $product->images->find();

but how can i actually take the second element? (using find eventually). Is there any easy solution for that?

thanks!


$first_two = $product->images->limit(2)->find_all();

find() is basically the same as find_all(), adding a limit(1) and returning the current result (first one).

$first = current($first_two);
$second = next($first_two);

Notice that next() advances the internal array pointer so you'll have to reset() it if you want to loop from the start again.


You can use limit($n) and offset($o) combination to select $n rows starting from $o position in DB. Read more about Query Builder methods here.

So, your code will looks like $image = $product->images->offset(1)->find();

PS. Note than some DB engines may not support SQL's OFFSET statement (MS SQL server for example).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜