Symfony 2 - 实体未更新

时间:2015-05-30 18:45:19

标签: symfony doctrine-orm

我正在处理旨在上传文件和更新Symfony2中的数据库的表单。我想手动设置book_id字段的值,而不是允许用户在表单中更改它。因此在我的控制器中使用doctrine来保存文档之前我正在调用:

$documents->setBookId('1');

Unluckilly我收到错误,表明该学说无法识别上述硬编码值输入。

An exception occurred while executing 'INSERT INTO Documents (book_id, marker, document_date, link, notes) VALUES (?, ?, ?, ?, ?)' with params [null, "fdd", "2015-04-04", null, "test"]:

在我看来,这可能与book_id字段与Books有关。因此可能我应该使用setBook函数。你能告诉我如何正确地做到这一点吗?

我的控制器文件如下所示:

/**
* This code is aimed at checking if the book is chosen and therefore whether any further works may be carried out
*/
$session = new Session();
if(!$session->get("App_Books_Chosen_Lp")) return new RedirectResponse($this->generateUrl('app_listbooks'));
// Authorization goes here 

$documents = new Documents();
$form = $this->createForm(new DocumentsType(), $documents);
$form->add('save', 'submit', array('label' => 'Dodaj dokument'));
$form->handleRequest($request);

if ($form->isValid()) {
    $em = $this->getDoctrine()->getManager();
    $documents->upload();
    $documents->setBookId('1');
    $em->persist($documents);
    $em->flush();

}
return $this->render('AppBundle:Documents:adddocuments.html.twig', array('form' => $form->createView()));

文档类:

<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * @ORM\Entity
 * @ORM\Table(name="Documents")
 * @ORM\HasLifecycleCallbacks
 */

class Documents
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Books", inversedBy="documents")
     * @ORM\JoinColumn(name="book_id", referencedColumnName="id")
     */
    protected $book;

    /**
     * @ORM\Column(type="integer")
     */
    protected $book_id;

    /**
     * @ORM\Column(type="string", length=220)
     */
    protected $marker;

    /**
     * @ORM\Column(type="date", length=220)
     */
    protected $document_date;

    /**
     * @ORM\Column(type="string", length=220)
     * @Assert\File(maxSize="6000000")
     */
     protected $link;

     /**
     * @ORM\Column(type="text")
     */
     protected $notes;


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set book_id
     *
     * @param integer $bookId
     * @return Documents
     */
    public function setBookId($bookId)
    {
        $this->book_id = $bookId;

        return $this;
    }

    /**
     * Get book_id
     *
     * @return integer 
     */
    public function getBookId()
    {
        return $this->book_id;
    }

    /**
     * Set marker
     *
     * @param string $marker
     * @return Documents
     */
    public function setMarker($marker)
    {
        $this->marker = $marker;

        return $this;
    }

    /**
     * Get marker
     *
     * @return string 
     */
    public function getMarker()
    {
        return $this->marker;
    }

    /**
     * Set document_date
     *
     * @param \DateTime $documentDate
     * @return Documents
     */
    public function setDocumentDate($documentDate)
    {
        $this->document_date = $documentDate;

        return $this;
    }

    /**
     * Get document_date
     *
     * @return \DateTime 
     */
    public function getDocumentDate()
    {
        return $this->document_date;
    }

    /**
     * Set link
     *
     * @param string $link
     * @return Documents
     */
    public function setLink($link)
    {
        $this->link = $link;

        return $this;
    }

    /**
     * Get link
     *
     * @return string 
     */
    public function getLink()
    {
        return $this->link;
    }


    /**
     * Set notes
     *
     * @param string $notes
     * @return Documents
     */
    public function setNotes($notes)
    {
        $this->notes = $notes;

        return $this;
    }

    /**
     * Get notes
     *
     * @return string 
     */
    public function getNotes()
    {
        return $this->notes;
    }

    /**
     * Set book
     *
     * @param \AppBundle\Entity\Books $book
     * @return Documents
     */
    public function setBook(\AppBundle\Entity\Books $book = null)
    {
        $this->book = $book;

        return $this;
    }

    /**
     * Get book
     *
     * @return \AppBundle\Entity\Books 
     */
    public function getBook()
    {
        return $this->book;
    }

    /*
    * ### FILE UPLOAD PROCESS ### 
    */

    /**
     * @Assert\File(maxSize="6000000")
     */
    private $file;

    /**
     * Sets file.
     *
     * @param UploadedFile $file
     */
    public function setFile(UploadedFile $file = null)
    {
        $this->file = $file;
    }

    /**
     * Get file.
     *
     * @return UploadedFile
     */
    public function getFile()
    {
        return $this->file;
    }

      public function getAbsolutePath()
    {
        return null === $this->path
            ? null
            : $this->getUploadRootDir().'/'.$this->path;
    }

    public function getWebPath()
    {
        return null === $this->path
            ? null
            : $this->getUploadDir().'/'.$this->path;
    }

    protected function getUploadRootDir()
    {
        // the absolute directory path where uploaded
        // documents should be saved
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw up
        // when displaying uploaded doc/image in the view.
        return 'uploads/documents';
    }

    public function upload()
    {
        // the file property can be empty if the field is not required
        if (null === $this->getFile()) {
            return;
        }

        // use the original file name here but you should
        // sanitize it at least to avoid any security issues

        // move takes the target directory and then the
        // target filename to move to
        $this->getFile()->move(
            $this->getUploadRootDir(),
            $this->getFile()->getClientOriginalName()
        );

        // set the path property to the filename where you've saved the file
        $this->path = $this->getFile()->getClientOriginalName();

        // clean up the file property as you won't need it anymore
        $this->file = null;
    }

}

1 个答案:

答案 0 :(得分:0)

好的,首先,由于您使用的是ManyToOne关系,因此您实际上并不需要其他属性来引用该书 - book_id。您可以将其删除并仅保留book

然后在您的控制器中,您必须查询该Book的数据库,并将该对象设置为Document

你可以这样做:

$bookId = 1; // Following your example, let's say tou already know the book ID.
$book = $em->getReference('AppBundle:Books', $bookId);

// Check if we actually found a record and then set it to Documents
// Looking at your entity mapping, your reference to Book can not be null,
// but doing an extra check never hurts, since this is just an example.
if( $book ) {
    $documents->setBook($book);
}

-Update -

如果您想直接插入bookID,那么在您的实体中使用ManyToOne引用的目的是什么?最终,您必须正确地开始使用学说的关系和对象。此外,关于getReference方法的一个很酷的事情是,您正在获取对实体的引用,而无需从数据库加载实体 - 您将获得所谓的Proxy objects

  

方法EntityManager#getReference($ entityName,$ identifier)允许您获取对已知标识符的实体的引用,而无需从数据库中加载该实体。例如,当您想要与具有标识符的实体建立关联时,这很有用,作为性能增强

您可以进一步了解此here.