Доступ к вложенным комментариям в блоге Symfony
Я работаю над проектом, который реализует общедоступный канал. У меня есть объект Comment
, который позволяет пользователям отправлять комментарии к каждому каналу. Однако я хочу, чтобы пользователи также могли отправлять ответы на комментарии.
Для этой цели у меня есть свойство $response
в моей сущности Comment
. Я предполагаю, что сохранение ответа аналогично сохранению комментария, поскольку ответ также является комментарием.
Но я не уверен в том, как я могу получить доступ к комментарию без его id
и сохранить ответ на этот комментарий.
В моем FeedController
Я сохраняю такой комментарий;
$commentForm = $this->createForm(CommentType::class);
$commentForm->handleRequest($request);
if ($commentForm->isSubmitted() && $commentForm->isValid()) {
$content = $commentForm->get('content')->getData();
$feed_id = $feed;
$comment= EntityBuilder::newComment($content, $user, $feed_id);
$commentService->saveEntity($comment);
if(!is_null($comment)){
$this->addFlash(
'commentsuccess',
'Your reply was successfully posted!'
);
}
return $this->redirect($this->generateUrl('showFeed', array('slug' => $feed->getSlug()), UrlGeneratorInterface::ABSOLUTE_URL));
}
Вот сущность комментария;
/**
* Class Comment
* @package AppBundle\Entity
* @ORM\Entity(repositoryClass="AppBundle\Repository\CommentRepository")
* @ORM\Table(name="comment")
* @ORM\HasLifecycleCallbacks()
*
*/
class Comment
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Feed", inversedBy="comments")
* @ORM\JoinColumn(name="feedid", referencedColumnName="id")
*/
private $feedid;
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="comments")
* @ORM\JoinColumn(name="createdby", referencedColumnName="id")
*/
private $createdby;
/**
* @ORM\Column(type="string")
* @Assert\NotBlank(message="Please fill in the description")
*/
private $content;
/**
* @ORM\OneToOne(targetEntity="Comment")
*/
protected $response;
/**
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @ORM\Column(type="datetime")
*/
private $updatedAt;
/**
* Constructor
*/
public function __construct()
{
$this->createdAt= new \DateTime();
$this->updatedAt= new \DateTime();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set content
*
* @param string $content
*
* @return Comment
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set feedid
*
* @param \AppBundle\Entity\Feed $feedid
*
* @return Comment
*/
public function setFeedid(\AppBundle\Entity\Feed $feedid = null)
{
$this->feedid = $feedid;
return $this;
}
/**
* Get feedid
*
* @return \AppBundle\Entity\Feed
*/
public function getFeedid()
{
return $this->feedid;
}
/**
* Set createdby
*
* @param \AppBundle\Entity\User $createdby
*
* @return Comment
*/
public function setCreatedby(\AppBundle\Entity\User $createdby = null)
{
$this->createdby = $createdby;
return $this;
}
/**
* Get createdby
*
* @return \AppBundle\Entity\User
*/
public function getCreatedby()
{
return $this->createdby;
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
*
* @return Comment
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* @param \DateTime $updatedAt
*
* @return Comment
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set response
*
* @param \AppBundle\Entity\Comment $response
*
* @return Comment
*/
public function setResponse(\AppBundle\Entity\Comment $response = null)
{
$this->response = $response;
return $this;
}
/**
* Get response
*
* @return \AppBundle\Entity\Comment
*/
public function getResponse()
{
return $this->response;
}
}
Даже если я создам другой тип формы для ответов, я все еще не уверен в том, как я могу сохранить ответ для конкретного комментария.
1 answers
Моя рекомендация состоит в том, чтобы реализовать подход "Родители/дети", добавив (ManyToOne
) $parent
поле для сущности Comment
и ее инвертированного
(OneToMany
) $children
собственность. Позже вы можете добавить поле формы CollectionType
в CommentType
для свойства $children
, поэтому вам может потребоваться более одного ответа на комментарий.
Не беспокойтесь о родителе id
, CollectionType
сделает всю работу за вас.
Подробнее о том, как CollectionType
работает , смотрите здесь.