Reg*_*tix 2 orm laravel eloquent laravel-5.7
我的 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);
}
Run Code Online (Sandbox Code Playgroud)
我需要检查比赛是否已经有了位置,所以我将比赛数据存储在里面$competition。之后,如果找不到该位置,我会将该位置附加到竞赛中。
问题在于正在运行的查询数量;一种用于比赛数据,一种用于在比赛地点内未找到时检索其 ID 的位置,另一种用于在附加时存储数据。
这会返回错误:“超出了最大执行时间 60 秒”
这样做的正确方法是什么?最大限度地减少所需的查询量。
提前致谢
您的查询似乎没问题,但 foreach 循环我认为它不好,所以更新代码如下:
$competition = Competition::where('id','=', $request->input('contestId'))->firstOrFail();
if($locationId = Location::where('name','=', $request->input('locationList'))->first()){
$competition->locations()->attach($locationId->id);
}
Run Code Online (Sandbox Code Playgroud)
如果位置存在则添加,否则不添加
public/index.php在文件中添加行功能
set_time_limit($seconds);
Run Code Online (Sandbox Code Playgroud)
否则增加max_execution_time并php.ini重新启动服务器
| 归档时间: |
|
| 查看次数: |
24688 次 |
| 最近记录: |