Laravel по-русски

Русское сообщество разработки на PHP-фреймворке Laravel.

Ты не вошёл. Вход тут.

#1 08.01.2021 14:13:37

Оптимизация контроллера, помогите.

Помогите пожалуйста, очень медленно работает при нагрузке в 70  человек с обновлением раз в 5 сек обрабатывается секунд 10-15

	
public function show(Request $request, $id)
	{
		$user = \Auth::user();

		$tournament = \Cache::remember('Tournament@show_' . $id, 5, function () use ($id) {
			return Tournament::select($this->select)->find($id);
		});
		$round = $request->get('round') ? $request->get('round') : $tournament->round;


		$grids = TGrids::select('*')
			->where('tournament_id', $tournament->id)
			->with(['matches' => function ($query) {
				$query->select(['grid_id', 'tournament_id', 'status', 'win', 'code']);
			}]);

		$TPlayersSelect = [
			'tournaments_players.user_id', 'tournaments_players.role', 'round',
			'team', 'nickname', 'avatar', 'exp', 'users.role AS site_role', 'grid_id'
		];

		if (\Perm::allows('tournament@info-role'))
			if (\Perm::role(['moder', 'admin', 'dev']))
				$TPlayersSelect = array_merge($TPlayersSelect, ['note']);

		$players = TPlayers::select($TPlayersSelect)
			->where('tournaments_players.tournament_id', 	$id)
			->join('users',						'users.id',						'=', 'tournaments_players.user_id')
			->join('games_accounts',	'games_accounts.id',	'=', 'tournaments_players.account_id')
			->with([
				'profile' => function ($query) use ($tournament) {
					$profileSelects = ['user_id', 'game', 'mmr'];

					if (\Perm::allows('tournament@info-role'))
						if (\Perm::role(['moder', 'admin', 'dev']))
							$profileSelects = array_merge($profileSelects, ['priority', 'roles']);

					$query->select($profileSelects);
					$query->where('game', $tournament->game);
				},
				'statistics' => function ($query) use ($tournament) {
					$query->select('user_id', 'win', 'lose');
					$query->where(DB::raw('DATE_FORMAT(created_at , \'%Y-%m\')'), date('Y-m'));
					$query->where('game', $tournament->game);
					$query->where('type',	$tournament->type);
				}
			]);

		if ($request->get('round') != 'all') {
			$grids->where('round', $round);
			$players->where('tournaments_players.round', $round);
		}

		$name = '_t' . $tournament->id . '_r' . $round . '_u-r' . $user->role;
		$players = \Cache::remember('TPlayers' . $name, 5, function () use ($players) {
			return $players->get();
		});

		if ($tournament->grid_disable) {
			$grids = [];
			$players = $players->map(function ($player, $key) {
				$player->team = null;
				$player->role = null;
				return $player;
			});
		} else {
			$grids = \Cache::remember('TGrids' . $name, 5, function () use ($grids) {
				return $grids->get();
			});

			if (\Perm::allows('tournament@edit', $tournament)) {
				$grids->each(function ($grid, $k) {
					$grid->matches->makeVisible(['code']);
				});
			} else {
				$player = $players->where('user_id', $user->id)
					->where('round', $tournament->round)->first();
				if ($player && $player->grid_id) {
					$grid = $grids->where('id', $player->grid_id)->first();
					if ($grid) $grid->matches->makeVisible(['code']);
				}
			}
		}

		$tournament->players = $players;
		$tournament->grids = $grids;

		return $tournament;
	}
class TGrids extends Model
{
	protected $table = 'tournaments_grids';
	
	public $timestamps = false;

	protected $fillable = [
		'tournament_id',
		'round', 'grid', 'bo',
		'win', 'team1', 'team2',
		'team1_score', 'team2_score'
	];
}
class TMatches extends Model
{
	protected $table = 'tournaments_matches';

	protected $fillable = [
		'tournament_id', 'grid_id',
		'status', 'win', 
		'code', 'match'
	];

	protected $hidden = ['code'];
}
class Tournament extends Model
{
	protected $fillable = [
		'user_id', 'provider_id',
		'name', 'img', 'desc', 'prize',
		'twitch', 'discord',
		'game', 'type', 'round',
		'lvl', 'max_players',
		'leave_disable', 'grid_disable',
		'start', 'status'
	];

	protected $casts = [
		'leave_disable' => 'boolean',
		'grid_disable'  => 'boolean'
	];
}
class GameProfile extends Model
{
	protected $table = 'games_profiles';

	protected $fillable = [
		'user_id', 'game',
		'mmr', 'priority', 'roles'
	];

	protected $casts = [
		'roles' => 'array',
		'mmr'		=> Rang::class
	];
}
class GameAccount extends Model
{
  protected $table = 'games_accounts';

  protected $fillable = [
		'user_id', 
		'game','nickname', 
		'profileId', 'accountId', 'active'
	];
}
class TStatistics extends Model
{
    protected $table = 'tournaments_statistics';

    protected $fillable = [
        'user_id', 'points',
        'game', 'type',
        'win', 'lose',
        'k', 'd', 'a'
    ];
}
class Rang implements CastsAttributes
{
	/**
	 * Cast the given value.
	 *
	 * @param  \Illuminate\Database\Eloquent\Model  $model
	 * @param  string  $key
	 * @param  mixed  $value
	 * @param  array  $attributes
	 * @return mixed
	 */
	public function get($model, $key, $value, $attributes)
	{
		$league = null;
		$division = null;

		foreach (config('games.lol.leagues') as $league_key => $divisions) {
			$divisions_key = array_reverse(array_keys($divisions));
			foreach ($divisions_key as $division_key) {
				$elo = $divisions[$division_key];

				if ($value >= $elo) {
					$league		= $league_key;
					$division = count($divisions_key) > 1 ? $division_key : null;
				} else return [
					'league'		=> $league,
					'division'	=> $division
				];
			}			
		}
		return [
			'league'		=> $league,
			'division'	=> $division
		];
	}
}

Изменено Ard2p (08.01.2021 14:16:34)

Не в сети

#2 23.01.2021 09:29:57

i3bepb
Откуда: Екатеринбург
Сообщений: 2

Re: Оптимизация контроллера, помогите.

Тут скорее всего проблемы в медленных запросах к БД, а не в коде контроллера, глядя только на код контроллера никто ничего не подскажет, надо структуру БД, затем какие запросы получаются. А еще в коде видно использование Cache::remember т.е. тот кто его писал уже знал, что есть проблемы с быстродействием и пытался, что-то закэшировать и вот когда кэша нет все тормозит.

Не в сети

Подвал раздела