Reputation: 291
I have a many to many relation in my laravel application.
The model Competition
belongsToMany Location
and vice versa.
Now I am trying to provide a functionality where one can add existing locations to a competition.
$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);
}
I need to check wheter the competition already has the location, so I store competition data inside $competition
. Afterwards, if the location was not found, I attach the location to the competition.
The problem is the amount of queries that are running; one for the competition data, one for the location to retrieve its id, when it hasn't been found inside the competition locations, and one to store the data when attaching.
This returns an error: "Maximum execution time of 60 seconds exceeded"
What is the correct way of doing so? To minimize the amount of queries needed.
Thanks in advance
Upvotes: 2
Views: 27934
Reputation: 15175
Your query is seems to be ok, but foreach loop i think it's not ok so update code like this:
$competition = Competition::where('id','=', $request->input('contestId'))->firstOrFail();
if($locationId = Location::where('name','=', $request->input('locationList'))->first()){
$competition->locations()->attach($locationId->id);
}
If location is there then added otherwise not added
Add line in public/index.php
file function
set_time_limit($seconds);
otherwise increase the max_execution_time
in php.ini
and restart server
Upvotes: 5
Reputation: 598
Just clear All Cache
step:1 Go your project directory and open command prompt
step:2 write command in command prompt php artisan optimize:clear
Then check your problem is solved...
Upvotes: 2
Reputation: 291
For some reason, the error didn't appear when I closed my Sqlite DB browser desktop program. Yet this is very strange, since I had the sqlite db browser app open since the beginning of my app creation.
Upvotes: -2