Laravel 超出最大执行时间 60 秒

问题描述 投票:0回答:3

我的 Laravel 应用程序中有多对多关系。 模型

Competition
属于ToMany
Location
,反之亦然。

现在我正在尝试提供一种功能,可以将现有位置添加到比赛中。

$competition    = Competition::where('id','=', $request->input('contestId'))->firstOrFail();
$locations      = $competition->locations;
$locationNames  = [];

foreach ($locations as $location) {
    $locationNames[] = $location->name;
}

if (!in_array($request->input('locationList'), $locationNames)) {
    $locationId = Location::where('name','=', $request->input('locationList'))->firstOrFail()->id;
    $competition->locations()->attach($locationId);
}

我需要检查比赛是否已经有位置,所以我将比赛数据存储在里面

$competition
。之后,如果找不到位置,我会将位置附加到比赛中。

问题在于正在运行的查询数量;一个用于比赛数据,一个用于在比赛位置内未找到时检索其 ID 的位置,一个用于在附加时存储数据。

这会返回错误:“超出最大执行时间 60 秒”

正确的做法是什么?最大限度地减少所需的查询量。

提前致谢

laravel orm eloquent laravel-5.7
3个回答
5
投票

您的查询似乎没问题,但 foreach 循环我认为它不好,所以更新代码如下:

$competition = Competition::where('id','=', $request->input('contestId'))->firstOrFail();

if($locationId = Location::where('name','=', $request->input('locationList'))->first()){
      $competition->locations()->attach($locationId->id);
}

如果位置存在则添加,否则不添加

public/index.php
文件中添加行功能

set_time_limit($seconds);

否则增加

max_execution_time
中的
php.ini
并重新启动服务器


1
投票

只需清除所有缓存即可

步骤:1 转到项目目录并打开命令提示符

步骤:2在命令提示符中写入命令php artisan optimize:clear

然后检查您的问题是否已解决...


-1
投票

由于某种原因,当我关闭 Sqlite DB 浏览器桌面程序时,错误没有出现。但这很奇怪,因为从我的应用程序创建开始我就打开了 sqlite db 浏览器应用程序。

© www.soinside.com 2019 - 2024. All rights reserved.