php 使用 Eloquent 的 Laravel 块方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39972653/
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-08-26 02:03:14  来源:igfitidea点击:

Laravel Chunk Method Using Eloquent

phpjsonlaravellaravel-5eloquent

提问by Aamir

For processing large database, laravel provides chunk method as here https://laravel.com/docs/5.1/queries#retrieving-results

为了处理大型数据库,laravel 提供了块方法,如这里https://laravel.com/docs/5.1/queries#retrieving-results

But how can I use chunk method in this query,

但是我如何在这个查询中使用块方法,

 $data = Inspector::latest('id')
                ->select('id', 'firstname', 'status', 'state', 'phone')
                ->where('firstname', 'LIKE', '%' . $searchtext . '%')
                ->get();

where I'm returning json response like this,

我在这里返回这样的 json 响应,

echo json_encode($data);

Any suggestions....

有什么建议....

回答by haakym

As I understand it the chunk()method is for use when you need to work with a large dataset and take an actionon that data chunk by chunk.

据我了解,该chunk()方法适用于需要处理大型数据集并逐块对该数据执行操作的情况。

From your question, it sounds like you're performing a query then returning the data as JSON so to me, it doesn't sound like you're taking an action on your dataset that requires chunking.

从您的问题来看,听起来您正在执行查询,然后将数据作为 JSON 返回,所以对我来说,这听起来不像您正在对需要分块的数据集执行操作。

If you want to break up the returned JSON data you should be instead looking at pagination.

如果您想分解返回的 JSON 数据,您应该查看pagination

You could apply pagination to your query like so:

您可以像这样将分页应用于您的查询:

$data = Inspector::latest('id')
    ->select('id', 'firstname', 'status', 'state', 'phone')
    ->where('firstname', 'LIKE', '%' . $searchtext . '%')
    ->paginate();

You can specify the size of each set by passing a number to the paginate method:

您可以通过将数字传递给 paginate 方法来指定每个集合的大小:

$data = Inspector::latest('id')
    ->select('id', 'firstname', 'status', 'state', 'phone')
    ->where('firstname', 'LIKE', '%' . $searchtext . '%')
    ->paginate(25);

If I've misunderstood and you did actually want to do the chunking, I believe you could do the following:

如果我误解了并且您确实想要进行分块,我相信您可以执行以下操作:

$data = Inspector::latest('id')
    ->select('id', 'firstname', 'status', 'state', 'phone')
    ->where('firstname', 'LIKE', '%' . $searchtext . '%')
    ->chunk(50, function($inspectors) {
        foreach ($inspectors as $inspector) {
            // apply some action to the chunked results here
        }
    });

Also, if you're returning an eloquent object it will be automatically cast to json so you don't need to perform json_encode()as far as I'm aware.

此外,如果您要返回一个 eloquent 对象,它将自动转换为 json,因此您不需要执行json_encode()我所知道的。

EDIT

编辑

If I've completely misunderstood you and what you actually want to do is this:

如果我完全误解了你,而你真正想做的是:

{ 1000 records } -> this is the result of your query

split it into this:

把它分成这个:

{
    { 300 records},
    { 300 records},
    { 300 records},
    { 100 records},
}

Then you want the Collection's chunk method:

然后你想要Collection's chunk 方法:

$data = Inspector::latest('id')
    ->select('id', 'firstname', 'status', 'state', 'phone')
    ->where('firstname', 'LIKE', '%' . $searchtext . '%')
    ->get() // now we're working with a collection
    ->chunk(300);

Remember you're not working with a Collectionuntil you get the result of the query so if you just call chunk()it will expect a callback, which will be applied to the entire dataset, as you're working with Eloquent.

请记住,在Collection获得查询结果之前,您不会使用 a ,因此,如果您只是调用chunk()它,则会期待一个回调,该回调将应用于整个数据集,因为您正在使用Eloquent.

See for further reading here on the Collectionchunk()method here: https://laravel.com/docs/5.3/collections#method-chunk

有关此处Collectionchunk()方法的进一步阅读,请参见此处:https: //laravel.com/docs/5.3/collections#method-chunk

Otherwise... Could you give some more context to what you're actually doing? It really sounds like you need pagination. What are you doing with the JSON data and how are you invoking the HTTP request, is it via ajax? Why do you need the whole 1000 records all at once?

否则......你能提供更多关于你实际在做什么的背景吗?听起来你真的需要分页。你在用 JSON 数据做什么,你如何调用 HTTP 请求,是通过 ajax 吗?为什么你一次需要全部 1000 条记录?

If you really need the whole dataset of 1000 sent to the client, but 300 at a time then you don't want to use chunk. Think about what chunk()is for in the context of eloquent, it's not for getting chunks to return to the client a chunk at a time until it has the whole data set - it's for applying an action to a chunk then returning the whole set and the point of using it is so it doesn't take up too much memory at one time by loading the whole set to process the action on.

如果您确实需要将 1000 个的整个数据集发送到客户端,但一次发送 300 个,那么您不想使用块。想想chunk()在 eloquent 的上下文中是什么,它不是为了让块一次返回给客户端一个块,直到它拥有整个数据集 - 它是为了将一个动作应用于一个块然后返回整个集和点使用它是为了通过加载整个集合来处理动作,它一次不会占用太多内存。

If you want the whole data set bit by bit and pagination won't work for your case (I'm yet to see why!) you will need to invoke the HTTP request several times to get the data bit by bit and specify in each request what you already have and what you need.

如果您希望整个数据集一点一点地进行,而分页对您的情况不起作用(我还没有明白为什么!),您将需要多次调用 HTTP 请求以一点一点地获取数据并在每个请求你已经拥有的和你需要的。

回答by ToNy

Instead of get()use chunk(). Eg. chunk(100, function($data) {})

而不是get()使用chunk(). 例如。 chunk(100, function($data) {})

回答by Kamil Kie?czewski

Chunk is not for return data by request but for processing large tables on server - here is simple example showing how to use it (tested on Laravel 5.7):

Chunk 不是用于按请求返回数据,而是用于处理服务器上的大表 - 这里是展示如何使用它的简单示例(在 Laravel 5.7 上测试):

User::chunk(100, function($users) {
    foreach ($users as $user) {
        // processing
    }
});

回答by rizky redjo

  1. can use variable $counter. and put
  1. 可以使用变量 $counter。并放
    if ($counter>=100) { break; }

  1. can called on view with
  1. 可以调用视图
    use path/models/User;
    Users->chunk(100, function($users) {
        foreach ($users as $user) {
            //
        }
    });