<filename>app/services/game_service.py
from typing import Optional, List

from sqlalchemy import select
from sqlalchemy.orm import selectinload

from app.database.models import Game, GameToGamer
from app.database.connection import DBSession
from app.schemes.game import AddPlayerToGame, GameCreate

from app.services.base_service import BaseService


class GameService(BaseService):
    _target_table = Game

    @classmethod
    async def all(cls, db_session: DBSession) -> List[Optional[Game]]:
        query = select(cls._target_table).options(selectinload(Game.players))
        result = await db_session.execute(query)
        return result.scalars().all()

    @classmethod
    async def create(cls, game_schame: GameCreate, session: DBSession) -> Game:
        game = Game(game_schame.ownerId)
        return game.write_record(session)

    @classmethod
    async def add_players(cls, scheme: AddPlayerToGame, session: DBSession) -> Game:
        """
        Add players to the Game
            """
        game_id = scheme.gameId
        game_to_players = []
        for player_id in scheme.playerIds:
            game_to_players.append(GameToPlayer(game_id, player_id))
        session.add_all(game_to_players)
        await session.commit()
        return await cls.get(game_id, session)

<filename>app/services/game_service.py
from typing import Optional, List

from sqlalchemy import select
from sqlalchemy.orm import selectinload

from app.database.models import Game, GameToGamer
from app.database.connection import DBSession
from app.schemes.game import AddPlayerToGame, GameCreate

from app.services.base_service import BaseService


class GameService(BaseService):
    _target_table = Game

    @classmethod
    async def all(cls, db_session: DBSession) -> List[Optional[Game]]:
        query = select(cls._target_table).options(selectinload(Game.players))
        result = await db_session.execute(query)
        return result.scalars().all()

    @classmethod
    async def create(cls, game_schame: GameCreate, session: DBSession) -> Game:
        game = Game(game_schame.ownerId)
        return game.write_record(session)

    @classmethod
    async def add_players(cls, scheme: AddPlayerToGame, session: DBSession) -> Game:
        """
        Add players to the Game
            """
        game_id = scheme.gameId
        game_to_players = []
        for player_id in scheme.playerIds:
            game_to_players.append(GameToPlayer(game_id, player_id))
        session.add_all(game_to_players)
        await session.commit()
        return await cls.get(game_id, session)

Add players to the Game