我在Laravel的日程安排上遇到了问题.
root@trafficshield:/var/www/vhosts/trafficshield.tools/httpdocs#
/opt/plesk/PHP/7.1/bin/PHP artisan schedule:run Running scheduled
command: Closure ^[[15~PHP Fatal error: Allowed memory size of
8589934592 bytes exhausted (tried to allocate 4096 bytes) in
/var/www/vhosts/trafficshield.tools/httpdocs/vendor/laravel/framework/src/Illum
inate/Database/Eloquent/Model.PHP on line 279 PHP
这个时间表旨在计算我们服务的所有访问的所有访问.
$schedule->call(function () {
$campaigns = Campaign::all();
foreach ($campaigns as $campaign) {
$campaign->denied_visits = $campaign->visitsDenied->count();
$campaign->allowed_visits = $campaign->visitsAllowed->count();
$campaign->save();
}
})->everyFiveMinutes();
配置:memory_limit:8G
在此先感谢您的帮助.
解决方法:
Allowed memory size of 8589934592 bytes exhausted
这种错误是由内存中的大量数据引起的,因此修复它的方法是编写一个不太重的内存脚本.通过更改memory_limit,我们只得到暂时的修复,因为当我们的数据增长时,它会回来.
$campaigns = Campaign::all(); //at this point you are pulling the whole Campaigns table to memory.. and you pull some extra rows after that increasing even more the memory use
正如我所说,Elloquent执行此类任务的效率很低,所以让我们像MysqLi一样逐个获取数据库行:
$db = DB::connection()->getPdo(); //get a database connection instance
$main_query_sql = "SELECT * FROM Campaigns"; //write our query
$main_query = $db->prepare($main_query_sql); //prepare it to get executed
$main_query->execute(); //execute our query
$visits_denied_sql = "SELECT COUNT(*) as total FROM VISITS WHERE DENIED = 1 AND CAMPAIGN_ID ="; //let's prepare our aggregate queries
$visits_allowed_sql = "SELECT COUNT(*) as total FROM VISITS WHERE DENIED = 0 AND CAMPAIGN_ID ="; //I just assumed them so change it as you need
$visits_denied = null;
$visits_allowed = null;
while($campaign = $main_query->fetch()){ //fetch our rows one by one
//Now we are getting an associative array from the db instead of a model so we cannot use it as a Laravel Model (we can't use ->save() method or eager loading)
$visits_denied = $db->prepare($visits_denied_sql.$campaign['id']);
$visits_denied = $visits_denied->execute();
$denied_visits = $visits_denied->fetch();
$visits_allowed= $db->prepare($visits_allowed_sql.$campaign['id']);
$visits_allowed= $visits_allowed->execute();
$allowed_visits = $visits_allowed->fetch();
$campaign['denied_visits'] = $denied_visits['total'];
$campaign['allowed_visits'] = $allowed_visits['total'] ;
//edit with the correct update sentence:
$insert_query_sql = "UPDATE CAMPAIGNS SET allowed_visits = :visits_allowed, denied_visits = :visits_denied WHERE id = :id";
$insert_query = $db->prepare($insert_query_sql);
$insert_query->bindParam(':visits_allowed', $campaign['allowed_visits']);
$insert_query->bindParam(':visits_denied', $campaign['denied_visits']);
$insert_query->bindParam(':id', $campaign['id']);
$insert_query->execute();
}
在你的日程表中试试这个,让我知道是否有效!