How to get one line at a time from an eloquent query in laravel?

Say I have a simple query to get all rows from a table:

App::make('My_Model')->get();

But I have a huge number of lines - say, 100,000, so many that PHP runs out of memory trying to read them all.

For some reason, I want to go through each of these lines and perform some operation based on them.

Is there any way to tell laravel to give me one row at a time how old mysql_fetch_row worked?

Note. I am currently solving this with limit () commands to get 5,000 rows at once, which works fine, except that it repeats the request 20 times.

I want to know if there is a built-in method in laravel or eloquent to give me the next line and not all the lines?

+4
source share
4 answers

If you want to process them, say a thousand at a time that method chunk()c Eloquentshould work for you:

My_Model::chunk(1000, function($my_models)
{
    foreach ($my_models as $my_model)
    {
        // do something
    }
});

More in Eloquent Documents

Depends on what you do with your data ...

+5
source

For anyone who lands here using Laravel 5.2+ (like me). Now there is an available cursor method that the generator returns

https://laravel.com/api/5.2/Illuminate/Database/Query/Builder.html#method_cursor

So, instead of -> get () use -> cursor ()

+5
source

, , ? , . Laravel , , 5000 , 5000 .

, paginate:

$someUsers = User::where('votes', '>', 100)->paginate(5000);

:

$page = 5;

$pageSize = 5000;

$users = User::skip($page * $pageSize)->take($pageSize)->get();

Chunk, paginagion, , :

User::chunk(5000, function($users)
{
    /// every time this clojure is ran you get a new subset of 5000 rows.

    foreach ($users as $user)
    {
        // do whatever you need with them
    }
});

Sidenote: , :

DB::disableQueryLog();
+1

? , 100 000 , , , 100 000 .

  • , , DB:: update(), , PHP
  • If you want to display only certain records, you can change your request to a model model so that you only load records into PHP memory that you really need.
  • If you really need to display the entire set of records, you really need to go through them in parts, but this does not look like what you are trying to do.

Give us more information, what are you really trying to accomplish?

0
source

Source: https://habr.com/ru/post/1534791/


All Articles