Doctrine ArrayCollection 插入后拒绝更新

我正在尝试保存一组文件。


当我保存集合时,它会顺利进入数据库。与文件相同。但是当我在同一请求中添加集合和新文件时(就像这里的上传功能一样)。每当我要求教义为我提供集合中的文件(在本例中为一个新文件)时。它总是以空的 ArrayCollection 进行响应。如果我执行单独的 get HTTP 请求并随后请求该集合,它会显示包含我的一个新文件的正确 arrayCollection。


我已经尝试了各种持久化和刷新实体的方法,以及更改级联注释,但到目前为止没有任何效果。我也尝试过清除教义缓存。


注释似乎是正确的,因为调用 getCollection()->getFiles() 会产生一个包含链接到该集合的文件的 ArrayCollection。创建两个实体并将它们链接在一起后似乎无法正常工作。


非常感谢您的帮助,代码在下面。


这是我的收藏。其中包含作为 ArrayCollection 的文件。


/**

 * @Entity @Table(name="LH_FileCollections")

 **/

class LhFileCollection extends RootModel

{

    /**

     * @Column(type="string")

     */

    protected $title;


    /**

     * @OneToMany(targetEntity="LhFile", mappedBy="collection")

     */

    protected $files;


    //Getters and Setters


}

这是我的文件类。


/**

 * @Entity @Table(name="LH_Files")

 **/

class LhFile extends RootModel

{

    /**

     * @Column(type="string")

     */

    protected $name;


    /**

     * @Column(type="string")

     */

    protected $type;


    /**

     * @Column(name="file_hash", type="string")

     */

    protected $fileHash;


    /**

     * @ManyToOne(targetEntity="LhFileCollection", inversedBy="files", cascade={"persist"})

     * @JoinColumn(name="collection_id", referencedColumnName="id")

     */

    protected $collection; 


    //Getters and Setters

}

这是我的保存文件收集功能。


/**

     * @return array|string

     * @throws \Doctrine\ORM\ORMException

     * @throws \Doctrine\ORM\OptimisticLockException

     * @throws \Exception

     */

    public function fileUpload(

        $title,

        $attachment = null,

        $allowedFileTypes = null,

        $maxAllowedFileSize = 5000000

    ) {


        //Create collection

        $collection = $this->fileCollectionRepository->add($title);


        foreach ($_FILES as $file) {

            if ($allowedFileTypes !== null) {

                $errors = $this->fileCheck($file, $allowedFileTypes, $maxAllowedFileSize);

                if (!empty($errors)) {

                    return $errors;

                }

            }

            $this->saveFile($file, $collection);

        }


        return $collection;

    }


潇潇雨雨
浏览 84回答 1
1回答

慕慕森

在我看来,在当前的请求中,我可以看出文件没有被添加到 collection->files 数组中。数据库正在接收正确的关系,这就是为什么在第二个请求时没有问题,但保存到数据库的行为不会自动填充关系。我认为您需要将文件显式添加到集合->文件中,假设您可以getFiles在LhFileCollection之后添加$this->saveFile($file, $collection);:$collection->getFiles()->add($file);当然有多种方法可以完成,但最终您需要将文件添加到集合->文件中。就个人而言,我会构建集合,将每个文件添加到文件数组中,然后才保存集合。我不会坚持并刷新每个文件,因为数据库操作可能会很昂贵。您已打开级联,因此它应该级联到所有文件。
打开App,查看更多内容
随时随地看视频慕课网APP