Eloquent request runs out of memory limit

I have a really very simple request

select * from `users` where (`active` = 1 and `newsletter` = 1) and (`terminated` = 0 or (`terminated` = 1 and `newsletter_terminated` = 1)); 

I build it with an eloquent like this (the above query is output when I do it with toSql()

 $recipients = User::where([ 'active' => 1, 'newsletter' => 1 ])->where(function ($query) { $query->where('terminated', 0) ->orWhere(function ($query){ $query->where('terminated', 1) ->where('newsletter_terminated', 1); }); })->get(); 

But when I execute this script, I get an error

 Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /xxx/eloquent/vendor/illuminate/database/Illuminate/Database/Connection.php on line 303 

When I write specific columns in the get method, for example get(['id']); It works without problems. But I still don't understand why this is not working. There seems to be a memory leak, but where?

When I execute a query in my SQL client, the query ends in 3 ms, so it doesn't seem like too much data is happening. Unfortunately, I do not have xdebug on the installed firewall, so I cannot get stacktrace at the moment.

+5
source share
2 answers

Something similar happened to me. Check the $ property with your model. You may have too many relationships loaded automatically. Try not to do this. Each object allocates memory. If you have 15,000 lines with many relationships and you look forward to loading each of them, the memory is reset. I ended up writing the original mysql query and resolving the problem.

+2
source

I had similar problems, and I don’t think that this is typical for Laravel - this is due to the built-in closures. Basically you are overflowing 128 MB for a process that interprets these closures, and this may not be enough for closed closures.

Try increasing your memory_limit in php.ini (512 MB should do the trick), expand the closure, or just use the raw SQL query to create this query.

+1
source

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


All Articles