获取 Doctrine 实体内的最大 id

问题描述 投票:0回答:4

我需要获取 symfony 2.7 实体内表的最大 ID。但我没有得到 id,而是遇到了这个问题。

注意:未定义的属性:AppBundle\Entity\BlogPost::$container

这是我的 BlogPost 实体,

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * BlogPost
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class BlogPost {

    const SERVER_PATH_TO_IMAGE_FOLDER = '/uploads';

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="body", type="text")
     */
    private $body;

    /**
     * @var string
     *
     * @ORM\Column(name="filename", type="text")
     */
    private $filename;

    /**
     * Set filename
     *
     * @param string $filename
     * @return BlogPost
     */
    public function setFilename($filename) {
        $this->filename = $filename;

        return $this;
    }

    public function setUploader(UploadedFile $file) {
        $em = $this->container->get('doctrine.orm.entity_manager');
        $highest_id = $em->createQueryBuilder()
                ->select('MAX(b.id)')
                ->from('AppBundle:BlogPost', 'b')
                ->getQuery()
                ->getSingleScalarResult();

        var_dump($highest_id);
        exit();// exit for check value

        $url = 'uploads/events';
        $file_name = 'fsdf.' . $file->guessExtension();
        $file->move($url, $file_name);
    }

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

    /**
     * @var boolean
     *
     * @ORM\Column(name="draft", type="boolean")
     */
    private $draft;

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

    /**
     * Set title
     *
     * @param string $title
     * @return BlogPost
     */
    public function setTitle($title) {
        $this->title = $title;

        return $this;
    }

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

    /**
     * Set body
     *
     * @param string $body
     * @return BlogPost
     */
    public function setBody($body) {
        $this->body = $body;

        return $this;
    }

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

    /**
     * Set draft
     *
     * @param boolean $draft
     * @return BlogPost
     */
    public function setDraft($draft) {
        $this->draft = $draft;

        return $this;
    }

    /**
     * Get draft
     *
     * @return boolean 
     */
    public function getDraft() {
        return $this->draft;
    }

    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="blogPosts")
     */
    private $category;

    public function setCategory(Category $category) {
        $this->category = $category;
    }

    public function getCategory() {
        return $this->category;
    }

    /**
     * Unmapped property to handle file uploads
     */
    public $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;
    }

    /**
     * Manages the copying of the file to the relevant place on the server
     */
    public function upload() {
        // the file property can be empty if the field is not required
        if (null === $this->getFile()) {
            return;
        }

        // we use the original file name here but you should
        // sanitize it at least to avoid any security issues
        // move takes the target directory and target filename as params
        $this->getFile()->move(
                self::SERVER_PATH_TO_IMAGE_FOLDER, $this->getFile()->getClientOriginalName()
        );

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

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

    /**
     * Lifecycle callback to upload the file to the server
     */
    public function lifecycleFileUpload() {
        $this->upload();
    }

    /**
     * Updates the hash value to force the preUpdate and postUpdate events to fire
     */
    public function refreshUpdated() {
//        $this->setUpdated(new \DateTime());
    }

// ... the rest of your class lives under here, including the generated fields
//     such as filename and updated
}

这是我试图获取最大 id 的部分,

public function setUploader(UploadedFile $file) {
        $em = $this->container->get('doctrine.orm.entity_manager');
        $highest_id = $em->createQueryBuilder()
                ->select('MAX(b.id)')
                ->from('AppBundle:BlogPost', 'b')
                ->getQuery()
                ->getSingleScalarResult();

        var_dump($highest_id);
        exit();// exit for check value

        $url = 'uploads/events';
        $file_name = 'fsdf.' . $file->guessExtension();
        $file->move($url, $file_name);
    }

在评论和少量研究的帮助下,我发现问题出在“entity_manager”部分。有没有办法在实体内部调用学说查询?

symfony doctrine-orm entity query-builder
4个回答
6
投票

如果我是你,我会做类似的事情:

控制器:

$blogPost= new BlogPost () ; 
$em = $this->getDoctrine()->getManager();
//..your code
// I assume you want to do that after a form post 
$blogPost = $form->getData();
$id = $em->getRepository('AppBundle:BlogPost')->getMaxId();
$blogPost->setUploader($id);
//...

存储库:

public function getMaxId()
{
    $qb = $this->createQueryBuilder('u');
    $qb->select('u, MAX(id) as idMax');  
    return $qb->getQuery()->getSingleResult();
}

实体:

public function setUploader(UploadedFile $file, $id)
{
    var_dump($id);
    $url = 'uploads/events';
    $file_name = 'fsdf.'.$id.$file->guessExtension();
    $file->move($url, $file_name);
}

应该有效


1
投票

我建议将

EntityManager
作为
class variable
保存在
Entity
中,并通过
constructor
或通过在使用 setUploader 函数之前调用的
setter-method
实例化它。

这应该是最干净、最好可读的解决方案。


1
投票

在您的控制器中尝试一下:

$blogPost= new BlogPost () ; 
$em = $this->getDoctrine()->getManager();
$blogPost = $form->getData();
$maxId = $em->getRepository('AppBundle:BlogPost')->createQueryBuilder('b')
    ->where("MAX(b.id) as maxId")
    ->getQuery()
    ->getSingleResult();

-2
投票

形成另一个线程,我发现了这个,它对我有用。

global $kernel;

if ( 'AppCache' == get_class($kernel) )
{
   $kernel = $kernel->getKernel();
}
$em = $kernel->getContainer()->get( 'doctrine.orm.entity_manager');

我无法在控制器中使用它,因为我有一个管理类而不是控制器。由于很多人建议在实体内使用entity_manager并不是一个好的做法,所以我使用管理类内的代码而不是实体。

这是原帖..
如何在Entity内部使用entityManager?

© www.soinside.com 2019 - 2024. All rights reserved.