我的 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 秒”
这样做的正确方法是什么?最大限度地减少所需的查询量。
提前致谢