口才限制和偏移量

这是我的

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

我只是想采取一个限制’产品’ 这样不对

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

请帮帮我!

Thanks!

419774 次浏览

请试试这样,

return Article::where('id',$article)->with(['products'=>function($products, $offset, $limit) {
return $products->offset($offset*$limit)->limit($limit);
}])

你可以使用 skiptake函数如下:

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

//skip应该作为整数值传递参数,以跳过记录和起始索引

//take获取一个整数值,以便在启动由 skip定义的索引之后获取记录数

剪辑

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.

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

例如:

$products = $art->products->forPage($page,$limit);
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

来自 Laravel 文件5.2 https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset

略过/取

限制从查询返回的结果数,或跳过 given number of results in the query (OFFSET), you may use the skip 并采取以下方法:

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

幼虫5.3你可以写(https://laravel.com/docs/5.3/queries#ordering-grouping-limit-and-offset)

$products = $art->products->offset(0)->limit(10)->get();

Try this sample code:

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


$products = $art->products->take($limit);

Laravel 对于 offset有自己的函数 skip,对于 limit有自己的函数 take

Article::where([['user_id','=',auth()->user()->id]])
->where([['title','LIKE',"%".$text_val."%"]])
->orderBy('id','DESC')
->skip(0)
->take(2)
->get();

Quick:

Laravel 有一个快速的分页方法 pagate,它只需要传递每页显示的数据数量。


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


how to customize paging:

你可以使用这些方法: offsetlimitskiptake

  • 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

例如:


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));
}
}




也许是这个

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

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);


$chunk = $collection->forPage(2, 3);


$chunk->all();

Laravel 5.1 < (当前 v 9)

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

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

$products = Article::orderBy('id', 'asc')->limit($limit)->get();