Я столкнулся с очень неприятной проблемой. У меня есть сущность Recipe, которая включает в себя некоторые ингредиенты (с сущностью Ingredient) с отношением ManyToMany и сущность RecipeIngredient для сопоставления.
Пользователи могут добавлять рецепт и указывать ингредиенты для этого рецепта с помощью текстового ввода.
Моя проблема в том, что когда пользователь вводит название ингредиента, которое уже есть в моей базе данных, я хочу получить его из своей базы данных и сопоставить его с новым рецептом и, очевидно, не настаивать на наличии двойных ингредиентов. p>
Recipe.php
/**
* @ORM\Entity
* @ORM\Table(name="recipe")
*/
class Recipe
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", unique=false)
*/
private $title;
/**
* @var array Ingredient[]
*/
private $ingredients;
/**
* @ORM\OneToMany(targetEntity="RecipeIngredient", mappedBy="recipe_id", cascade={"all"})
*/
private $recipeIngredients;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="recipes")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
}
Ingredient.php
/**
* @ORM\Entity()
* @UniqueEntity(
* fields={"name"}
* )
* @ORM\Table(name="ingredient")
*/
class Ingredient
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string")
*/
private $name;
/**
* @ORM\OneToMany(targetEntity="RecipeIngredient", mappedBy="ingredient_id", fetch="EXTRA_LAZY", cascade={"all"})
*/
private $recipesIngredient;
}
RecipeIngredient.php
/**
* Class RecipesIngredient
* @package AppBundle\Entity
*
* @ORM\Entity
* @ORM\Table(name="recipe_ingredient")
*/
class RecipeIngredient
{
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Recipe", inversedBy="recipeIngredients", cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $recipe;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Ingredient", inversedBy="recipesIngredient", cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $ingredient;
}
Спасибо за помощь.
РЕДАКТИРОВАТЬ
Функция создания рецепта
/**
* Creates a new recipe entity.
*
* @Route("/new/recipe", name="recipe_new")
* @Method({"GET", "POST"})
*
* @param $request Request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function newAction(Request $request)
{
$needAccount = true;
if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY') || $this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$needAccount = false;
}
$recipe = null;
$error = $request->getSession()->get("loginError");
$errorMsg = "";
if ($error !== null) {
$errorMsg = $error->getMessageKey();
}
$request->getSession()->remove("loginError");
if (!$needAccount) {
$recipe = new Recipe($this->getUser());
$form = $this->createForm('AppBundle\Form\RecipeType', $recipe);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->setRecipe($recipe);
$em = $this->getDoctrine()->getManager();
$em->persist($recipe);
$em->flush();
$mail = (new \Swift_Message("Nouvelle recette"))
->setFrom("*************")
->setTo("*********")
->setBody(
"Une recette vient d'être créée : *********" . $recipe->getUrl(),
'text/plain'
);
$this->get("mailer")->send($mail);
return $this->redirectToRoute('recipe_show', array('url' => $recipe->getUrl()));
}
return $this->render('@App/pages/recipe/new.html.twig', array(
'needAccount' => $needAccount,
"errorLogin" => $errorMsg,
'recipe' => $recipe,
'form' => $form->createView()
));
} else {
$recipe = new Recipe(new User());
return $this->render('@App/pages/recipe/new.html.twig', array(
'needAccount' => $needAccount,
"errorLogin" => $errorMsg,
'recipe' => $recipe,
'form' => null
));
}
}
Функция setRecipe
private function setRecipe(Recipe $recipe)
{
if ($recipe->getUrl() === "") {
$recipe->setUrl(preg_replace('/[^a-z0-9]+/', '-', strtolower(str_replace(explode(",", "ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,ø"), explode(",", "c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,o"), $recipe->getTitle()))) . '-' . time());
}
$recipe->setUpdatedAt(new \DateTime());
foreach ($recipe->getSteps() as $step) {
$step->setRecipe($recipe);
$step->setDescription(preg_replace_callback(
'/\\\\x([a-f0-9]{2})/i',
function ($matches) {
return chr(hexdec($matches[1]));
},
$step->getDescription()));
}
foreach ($recipe->getIngredients() as $ingredient) {
$ingredient->setName(preg_replace_callback('/\\\\x([a-f0-9]{2})/i',
function ($matches) {
return chr(hexdec($matches[1]));
},
$ingredient->getName()));
$ingredientExists = count($this->getDoctrine()->getManager()->getRepository('AppBundle:Ingredient')->createQueryBuilder('i')
->select('i.id')
->where('i.name LIKE :name')
->setParameter('name', '%' . $ingredient->getName() . '%')
->getQuery()
->execute()) > 0;
if (!$ingredientExists) {
$this->getDoctrine()->getManager()->persist($ingredient);
$this->getDoctrine()->getManager()->flush();
$addedIngredient = $this->getDoctrine()->getManager()->getRepository('AppBundle:Ingredient')->createQueryBuilder('i')
->select('i.id')
->where('i.name LIKE :name')
->setParameter('name', '%' . $ingredient->getName() . '%')
->getQuery()
->execute();
$ingredient->setId($addedIngredient[0]['id']);
} else {
$recipe->removeIngredient($ingredient);
$ingredientBDD = $this->getDoctrine()->getManager()->getRepository('AppBundle:Ingredient')->createQueryBuilder('i')
->select('i.id, i.name')
->where('i.name LIKE :name')
->setParameter('name', '%' . $ingredient->getName() . '%')
->getQuery()
->execute()[0];
$ingredient->setId($ingredientBDD["id"]);
$ingredient->setName($ingredientBDD["name"]);
}
$recipeIngredient = new RecipeIngredient();
$recipeIngredient->setIngredient($ingredient);
$recipeIngredient->setRecipe($recipe);
$recipeIngredient->setQuantity($ingredient->getQuantity());
$recipeIngredient->setUnity($ingredient->getUnity());
$recipe->addRecipeIngredient($recipeIngredient);
$ingredient->addRecipeIngredient($recipeIngredient);
}
}
Подробнее здесь: https://stackoverflow.com/questions/481 ... y-relation
Symfony 3.4 - Сохраняться, если не существует в отношении многотомного ⇐ Php
Кемеровские программисты php общаются здесь
1729310873
Anonymous
Я столкнулся с очень неприятной проблемой. У меня есть сущность Recipe, которая включает в себя некоторые ингредиенты (с сущностью Ingredient) с отношением ManyToMany и сущность RecipeIngredient для сопоставления.
Пользователи могут добавлять рецепт и указывать ингредиенты для этого рецепта с помощью текстового ввода.
Моя проблема в том, что когда пользователь вводит название ингредиента, которое уже есть в моей базе данных, я хочу получить его из своей базы данных и сопоставить его с новым рецептом и, очевидно, не настаивать на наличии двойных ингредиентов. p>
[b]Recipe.php[/b]
/**
* @ORM\Entity
* @ORM\Table(name="recipe")
*/
class Recipe
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", unique=false)
*/
private $title;
/**
* @var array Ingredient[]
*/
private $ingredients;
/**
* @ORM\OneToMany(targetEntity="RecipeIngredient", mappedBy="recipe_id", cascade={"all"})
*/
private $recipeIngredients;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="recipes")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
}
[b]Ingredient.php[/b]
/**
* @ORM\Entity()
* @UniqueEntity(
* fields={"name"}
* )
* @ORM\Table(name="ingredient")
*/
class Ingredient
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string")
*/
private $name;
/**
* @ORM\OneToMany(targetEntity="RecipeIngredient", mappedBy="ingredient_id", fetch="EXTRA_LAZY", cascade={"all"})
*/
private $recipesIngredient;
}
[b]RecipeIngredient.php[/b]
/**
* Class RecipesIngredient
* @package AppBundle\Entity
*
* @ORM\Entity
* @ORM\Table(name="recipe_ingredient")
*/
class RecipeIngredient
{
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Recipe", inversedBy="recipeIngredients", cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $recipe;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Ingredient", inversedBy="recipesIngredient", cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $ingredient;
}
Спасибо за помощь.
РЕДАКТИРОВАТЬ
Функция создания рецепта
/**
* Creates a new recipe entity.
*
* @Route("/new/recipe", name="recipe_new")
* @Method({"GET", "POST"})
*
* @param $request Request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function newAction(Request $request)
{
$needAccount = true;
if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY') || $this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$needAccount = false;
}
$recipe = null;
$error = $request->getSession()->get("loginError");
$errorMsg = "";
if ($error !== null) {
$errorMsg = $error->getMessageKey();
}
$request->getSession()->remove("loginError");
if (!$needAccount) {
$recipe = new Recipe($this->getUser());
$form = $this->createForm('AppBundle\Form\RecipeType', $recipe);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->setRecipe($recipe);
$em = $this->getDoctrine()->getManager();
$em->persist($recipe);
$em->flush();
$mail = (new \Swift_Message("Nouvelle recette"))
->setFrom("*************")
->setTo("*********")
->setBody(
"Une recette vient d'être créée : *********" . $recipe->getUrl(),
'text/plain'
);
$this->get("mailer")->send($mail);
return $this->redirectToRoute('recipe_show', array('url' => $recipe->getUrl()));
}
return $this->render('@App/pages/recipe/new.html.twig', array(
'needAccount' => $needAccount,
"errorLogin" => $errorMsg,
'recipe' => $recipe,
'form' => $form->createView()
));
} else {
$recipe = new Recipe(new User());
return $this->render('@App/pages/recipe/new.html.twig', array(
'needAccount' => $needAccount,
"errorLogin" => $errorMsg,
'recipe' => $recipe,
'form' => null
));
}
}
Функция setRecipe
private function setRecipe(Recipe $recipe)
{
if ($recipe->getUrl() === "") {
$recipe->setUrl(preg_replace('/[^a-z0-9]+/', '-', strtolower(str_replace(explode(",", "ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,ø"), explode(",", "c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,o"), $recipe->getTitle()))) . '-' . time());
}
$recipe->setUpdatedAt(new \DateTime());
foreach ($recipe->getSteps() as $step) {
$step->setRecipe($recipe);
$step->setDescription(preg_replace_callback(
'/\\\\x([a-f0-9]{2})/i',
function ($matches) {
return chr(hexdec($matches[1]));
},
$step->getDescription()));
}
foreach ($recipe->getIngredients() as $ingredient) {
$ingredient->setName(preg_replace_callback('/\\\\x([a-f0-9]{2})/i',
function ($matches) {
return chr(hexdec($matches[1]));
},
$ingredient->getName()));
$ingredientExists = count($this->getDoctrine()->getManager()->getRepository('AppBundle:Ingredient')->createQueryBuilder('i')
->select('i.id')
->where('i.name LIKE :name')
->setParameter('name', '%' . $ingredient->getName() . '%')
->getQuery()
->execute()) > 0;
if (!$ingredientExists) {
$this->getDoctrine()->getManager()->persist($ingredient);
$this->getDoctrine()->getManager()->flush();
$addedIngredient = $this->getDoctrine()->getManager()->getRepository('AppBundle:Ingredient')->createQueryBuilder('i')
->select('i.id')
->where('i.name LIKE :name')
->setParameter('name', '%' . $ingredient->getName() . '%')
->getQuery()
->execute();
$ingredient->setId($addedIngredient[0]['id']);
} else {
$recipe->removeIngredient($ingredient);
$ingredientBDD = $this->getDoctrine()->getManager()->getRepository('AppBundle:Ingredient')->createQueryBuilder('i')
->select('i.id, i.name')
->where('i.name LIKE :name')
->setParameter('name', '%' . $ingredient->getName() . '%')
->getQuery()
->execute()[0];
$ingredient->setId($ingredientBDD["id"]);
$ingredient->setName($ingredientBDD["name"]);
}
$recipeIngredient = new RecipeIngredient();
$recipeIngredient->setIngredient($ingredient);
$recipeIngredient->setRecipe($recipe);
$recipeIngredient->setQuantity($ingredient->getQuantity());
$recipeIngredient->setUnity($ingredient->getUnity());
$recipe->addRecipeIngredient($recipeIngredient);
$ingredient->addRecipeIngredient($recipeIngredient);
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/48148863/symfony-3-4-persist-if-not-exists-on-manytomany-relation[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия