Laravel Eloquent limit and offset

前端 未结 9 981
陌清茗
陌清茗 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 05:55

    Laravel 8 (This is worked for the version 7.16)

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

    https://laravel.com/docs/8.x/collections#method-take

    0 讨论(0)
  • 2020-12-13 05:56

    Please try like this,

    return Article::where('id',$article)->with(['products'=>function($products, $offset, $limit) {
        return $products->offset($offset*$limit)->limit($limit);
    }])
    
    0 讨论(0)
  • 2020-12-13 06:00

    laravel have own function skip for offset and take for limit. just like below example of laravel query :-

    Article::where([['user_id','=',auth()->user()->id]])
                    ->where([['title','LIKE',"%".$text_val."%"]])
                    ->orderBy('id','DESC')
                    ->skip(0)
                    ->take(2)
                    ->get();
    
    0 讨论(0)
  • 2020-12-13 06:01

    Try this sample code:

    $art = Article::where('id',$article)->firstOrFail();
    
    $products = $art->products->take($limit);
    
    0 讨论(0)
  • 2020-12-13 06:13

    Quick:

    Laravel has a fast pagination method, paginate, which only needs to pass in the number of data displayed per page.

    
    //use the paginate
    Book::orderBy('updated_at', 'desc')->paginate(8);
    
    

    how to customize paging:

    you can use these method: offsetlimit ,skiptake

    • offset,limit : where does the offset setting start, limiting the amount of data to be queried

    • skip,take: skip skips a few pieces of data and takes a lot of data

    for example:

    
    Model::offset(0)->limit(10)->get();
    
    Model::skip(3)->take(3)->get();
    
    
    //i use it in my project, work fine ~
    
    class BookController extends Controller
    {
        public function getList(Request $request) {
    
            $page = $request->has('page') ? $request->get('page') : 1;
            $limit = $request->has('limit') ? $request->get('limit') : 10;
    
            $books = Book::where('status', 0)->limit($limit)->offset(($page - 1) * $limit)->get()->toArray();
    
            return $this->getResponse($books, count($books));
        }
    }
    
    
    
    0 讨论(0)
  • 2020-12-13 06:13

    Maybe this

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

    0 讨论(0)
提交回复
热议问题