Symfony 3 - 如何防止 sql table 重复行
Symfony 3 - how to prevent sql table from duplicate rows
我正在 Symfony3 中创建 API,我遇到了用户可以将游戏添加到他的堆栈中的情况。所以我有连接用户 ID 和游戏 ID 的 table,但是当我将行添加到数据库时,可能会出现重复的情况,例如:
我想避免那种情况,但是该怎么做呢?是否有一些类似 symfony3 的方法可以防止这种情况发生?或者我应该在端点中添加一些 if-else 语句和 return 一些 JSON with success: false?无论如何,我该怎么做?我正在寻找最简单或最有效的方法。
实体代码如下:
<?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;
}
}
和 REST 端点:
<?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));
}
}
将 UniqueEntity
约束添加到您的实体并使用控制器中的 validator service 验证对象:
AppBundle/Entity/GamesOnStacks.php
<?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")
*
* @UniqueEntity( fields={"user", "game"}, errorPath="game", message="This game is already added on this user stack.")
*/
class GamesOnStacks
{
...
}
AppBundle/Controller/GameController
/**
* @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);
// validate using the validator service
$validator = $this->get('validator');
$errors = $validator->validate($gameOnStack);
if (count($errors) > 0) {
// custom error handling, e.g. returning failure jsonreponse, etc.
$errorsString = (string) $errors;
} else {
$em->persist($gameOnStack);
$em->flush();
$arr = array('success' => true);
return new JsonResponse(json_encode((array)$arr));
}
}
我正在 Symfony3 中创建 API,我遇到了用户可以将游戏添加到他的堆栈中的情况。所以我有连接用户 ID 和游戏 ID 的 table,但是当我将行添加到数据库时,可能会出现重复的情况,例如:
我想避免那种情况,但是该怎么做呢?是否有一些类似 symfony3 的方法可以防止这种情况发生?或者我应该在端点中添加一些 if-else 语句和 return 一些 JSON with success: false?无论如何,我该怎么做?我正在寻找最简单或最有效的方法。
实体代码如下:
<?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;
}
}
和 REST 端点:
<?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));
}
}
将 UniqueEntity
约束添加到您的实体并使用控制器中的 validator service 验证对象:
AppBundle/Entity/GamesOnStacks.php
<?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")
*
* @UniqueEntity( fields={"user", "game"}, errorPath="game", message="This game is already added on this user stack.")
*/
class GamesOnStacks
{
...
}
AppBundle/Controller/GameController
/**
* @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);
// validate using the validator service
$validator = $this->get('validator');
$errors = $validator->validate($gameOnStack);
if (count($errors) > 0) {
// custom error handling, e.g. returning failure jsonreponse, etc.
$errorsString = (string) $errors;
} else {
$em->persist($gameOnStack);
$em->flush();
$arr = array('success' => true);
return new JsonResponse(json_encode((array)$arr));
}
}