douchun2158 2018-01-03 06:34
浏览 79
已采纳

Symfony 2 - 从表中获取最后一个插入的行

How can I rewrite this code in order to get last inserted record from the table?

$repository = $entityManager->getRepository('AdminBundle:MyTable');
$product = $repository->find($id);

I tried something like

$repository->findBy(array('id','DESC')->setMaxResults(1);

But it did not work for me.

  • 写回答

3条回答 默认 最新

  • dqsvf28682 2018-01-03 06:48
    关注

    You could get the latest record by using findBy() with order by and limit paramters

    $results = $repository->findBy(array(),array('id'=>'DESC'),0,1);
    
    • First argument is for filter criteria
    • Second argument takes order by criteria
    • Third argument is for limit
    • Fourth argument sets offset

    Note it will return you the results set as array of objects so you can get single object from result as $results[0]

    FindBy() Examples

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dro7152 2018-01-03 06:48
    关注

    Please try the below one

    $repository = $entityManager->getRepository('AdminBundle:MyTable');
    $repository->setMaxResults(1)->orderBy('id', 'DESC');
    $results = $repository->getQuery()->getSingleResult();
    

    Reference: https://undebugable.wordpress.com/2016/01/27/symfony2-querybuilder-find-first-and-find-last-record-in-table/

    评论
  • dtrphb5597 2018-01-03 09:40
    关注

    Instead of hacking code where you want to use it, you can also create a repository method and call it when necessary.

    /**
     * Repository method for finding the newest inserted
     * entry inside the database. Will return the latest
     * entry when one is existent, otherwise will return
     * null.
     *
     * @return MyTable|null
     */
    public function findLastInserted()
    {
        return $this
            ->createQueryBuilder("e")
            ->orderBy("id", "DESC")
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }
    

    References: https://symfony.com/doc/current/doctrine.html#querying-for-objects-the-repository

    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 相同型号电脑与配置,发现主板有一台貌似缺少了好多元器件似的,会影响稳定性和使用寿命吗?
  • ¥15 要求编写稀疏矩阵A的转置矩阵的算法
  • ¥15 编写满足以下要求的停车场管理程序,设停车场只有一个可停放n辆车的狭窄通道且只有一个大门可供车辆进出。
  • ¥20 powerbulider 导入excel文件,显示不完整
  • ¥15 用keil调试程序保证结果进行led相关闪烁
  • ¥15 paddle训练自己的数据loss降不下去
  • ¥20 用matlab的pdetool解决以下三个问题
  • ¥15 单个福来轮的平衡与侧向滑动是如何做到的?
  • ¥15 嵌入式Linux固件,能直接告诉我crc32校验的区域在哪不,内核的校验我已经找到了,uboot没有
  • ¥20 h3c静态路要求有详细过程