Symfony 获取实体内的最大id

Symfony 获取实体内的最大id,symfony,doctrine-orm,entity,query-builder,Symfony,Doctrine Orm,Entity,Query Builder,我需要获得symfony 2.7实体内部表的最大ID。但是我没有身份证,而是得到了这个问题 注意:未定义的属性:AppBundle\Entity\BlogPost::$container 这是我的博客实体 <?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\HttpFoundation\File\UploadedFile; /** * BlogPost *

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

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

这是我的博客实体

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

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

如果我是你,我会这样做:

控制器:

存储库:

实体:

它应该可以工作

在控制器中尝试以下操作:


从另一个线程我发现了这个,它的工作为我

global $kernel;
if ( 'AppCache' == get_class($kernel) )
{
   $kernel = $kernel->getKernel();
}
$em = $kernel->getContainer()->get( 'doctrine.orm.entity_manager');
我不能在控制器中使用它,因为我有一个管理类而不是控制器。因为很多人建议在实体中使用实体管理器不是一个好的实践,所以我在admin类中使用代码而不是实体

这是原始线程。。

我建议将EntityManager作为类变量保存在实体中,并通过构造函数或在使用setUploader函数之前调用的setter方法对其进行实例化


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

您是否在某个时候设置了$This->container?你也应该重新考虑这一点,你的模型类不应该知道容器。这是你对实体管理器的要求,我不知道你是否可以在实体类中这样做。尝试在存储库类中执行此操作,并在控制器中执行逻辑。此外,在一个实体中调用em不是一个好的做法,除了所有其他人所说的不要在一个实体中调用em!这可能是一个坏的做法,要求最高的id无论如何-你能解释一下为什么你会需要它吗?我真的很抱歉,但很遗憾,我不能在这上面使用控制器哦,好吧,看看这篇文章的回应。他解释了如何在实体中使用em。老实说,我之前查看了解决方案,但我不明白。我真的很抱歉,但我对这个有点陌生。。。如果您可以修改它并添加到您的答案中,这将对我有很大帮助,我肯定会接受它作为正确的答案:@vimuth如果您是新手,那么请相信我们,当我们说您不应该在实体内部拥有存储库[或更糟糕的容器]访问权限时。多花点时间,找到一个没有它的解决方案。
$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);
}
$blogPost= new BlogPost () ; 
$em = $this->getDoctrine()->getManager();
$blogPost = $form->getData();
$id = $em->getRepository('AppBundle:BlogPost')->createQueryBuilder('b')
    ->where("MAX(b.id) as id")
    ->getQuery()
    ->getResult();
global $kernel;
if ( 'AppCache' == get_class($kernel) )
{
   $kernel = $kernel->getKernel();
}
$em = $kernel->getContainer()->get( 'doctrine.orm.entity_manager');