Laravel Eloquent limit and offset

前端 未结 9 982
陌清茗
陌清茗 2020-12-13 05:25

This is mine

    $art = Article::where(\'id\',$article)->firstOrFail();
    $products = $art->products;

I just wanna take a limit \'p

相关标签:
9条回答
  • 2020-12-13 06:14
    skip = OFFSET
    $products = $art->products->skip(0)->take(10)->get(); //get first 10 rows
    $products = $art->products->skip(10)->take(10)->get(); //get next 10 rows
    

    From laravel doc 5.2 https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset

    skip / take

    To limit the number of results returned from the query, or to skip a given number of results in the query (OFFSET), you may use the skip and take methods:

    $users = DB::table('users')->skip(10)->take(5)->get();

    In laravel 5.3 you can write (https://laravel.com/docs/5.3/queries#ordering-grouping-limit-and-offset)

    $products = $art->products->offset(0)->limit(10)->get(); 
    
    0 讨论(0)
  • 2020-12-13 06:16

    You can use skip and take functions as below:

    $products = $art->products->skip($offset*$limit)->take($limit)->get();
    

    // skip should be passed param as integer value to skip the records and starting index

    // take gets an integer value to get the no. of records after starting index defined by skip

    EDIT

    Sorry. I was misunderstood with your question. If you want something like pagination the forPage method will work for you. forPage method works for collections.

    REf : https://laravel.com/docs/5.1/collections#method-forpage

    e.g

    $products = $art->products->forPage($page,$limit);
    
    0 讨论(0)
  • 2020-12-13 06:19
    $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
    
    $chunk = $collection->forPage(2, 3);
    
    $chunk->all();
    
    0 讨论(0)
提交回复
热议问题