Symfony 2-实体未更新

Symfony 2-实体未更新,symfony,doctrine-orm,Symfony,Doctrine Orm,我正在使用表单,旨在上传文件并更新Symfony2中的数据库。我想手动设置book_id字段的值,不允许用户在表单中更改它。因此,在使用条令保存我调用的文档之前,在我的控制器中: $documents->setBookId('1'); 不幸的是,我得到了一个错误,表明条令无法识别上述硬编码值输入 An exception occurred while executing 'INSERT INTO Documents (book_id, marker, document_date, lin

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

$documents->setBookId('1');
不幸的是,我得到了一个错误,表明条令无法识别上述硬编码值输入

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字段与书籍相关这一事实有关。因此,我可能应该改用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()));
$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);
}
文件类别:

<?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;
    }

}

好的,首先,由于您使用的是
多通
关系,因此实际上不需要另一个引用图书的属性-
图书id
。您可以将其删除,只保留
书本

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

您可以这样做:

/**
* 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()));
$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);
}
-更新- 如果您想直接插入bookID,那么在您的实体中有
manytone
引用的目的是什么?最终你必须开始正确地使用条令的关系和对象。另外,
getReference
方法最酷的一点是,您可以获取对实体的引用,而不必从数据库加载实体-您可以获得所谓的
代理对象

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


您可以进一步了解这一点

,但我不是以这种方式向数据库生成不必要的查询吗?我这样问就好像我要手动建立这个关系(仅使用SQL查询),我只需在这个字段中输入bookID,这将为我节省一个查询。@Abdel5我已经添加了更多关于这个的信息。谢谢,我现在一切都清楚了。谢谢你为我提供了文档链接,这总是很有帮助的。上面的代码有点简化。我将使用$session->get(“App\u Books\u selected\u Lp”)作为“book\u id”的值,因此该值实际上会有所不同。这就是为什么我们有很多关系。