I'm creating API in Symfony3 and I have a situation where the user can add games to his stack. So I have the table which connects user id's and game id's, but when I'm adding rows to DB with that there can be a situation where there can be duplicates, like:
I want to avoid that situation, but how to do it? Are some symfony3-like ways to prevent that kind of situation? Or should I add some if-else statements in the endpoint and return some JSON with success: false? Anyway, how can I do it? I'm looking for the easiest or the most efficient way.
The code of the entity looks like:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="games_on_stacks")
*/
class GamesOnStacks
{
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="User")
*
*/
private $user;
/**
* @return mixed
*/
public function getUser()
{
return $this->user;
}
/**
* @param mixed $user
*/
public function setUser(User $user)
{
$this->user = $user;
}
/**
* @ORM\ManyToOne(targetEntity="Game")
*/
private $game;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @return mixed
*/
public function getGame()
{
return $this->game;
}
/**
* @param mixed $game
*/
public function setGame($game)
{
$this->game = $game;
}
}
and the REST endpoint:
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Game;
use AppBundle\Entity\GamesOnStacks;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
class GameController extends Controller
{
(...)
/**
* @Route("/game/{gameId}/add", name="game_add_to_stack")
*/
public function addToStack($gameId)
{
$gameOnStack = new GamesOnStacks();
// db apply
$em = $this->getDoctrine()->getManager();
$game = $em->getRepository('AppBundle:Game')
->findOneBy(['id' => $gameId]);
$gameOnStack->setGame($game);
$user = $em->getRepository('AppBundle:User')
->findOneBy(['id' => 1]);
$gameOnStack->setUser($user);
$em->persist($gameOnStack);
$em->flush();
$arr = array('success' => true);
return new JsonResponse(json_encode((array)$arr));
}
}