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

11

我该如何重写这段代码以获取表中最后插入的记录?

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

我尝试了类似的东西

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

但对我来说没有起作用。

6个回答

26

通过使用带有 order by、limit 和 offset 参数的 findBy(),您可以获取最新的记录。

$results = $repository->findBy(array(),array('id'=>'DESC'),1,0);
  • 第一个参数用于过滤条件
  • 第二个参数用于排序条件
  • 第三个参数是限制返回结果数量的
  • 第四个参数设置偏移量

请注意,它将作为对象数组返回结果集,因此您可以从结果中获取单个对象,例如$results[0]

FindBy()示例


我使用了你的代码,但是出现了以下错误:"[Doctrine\ORM\ORMException] Invalid order by orientation specified for Backend\AdminBundle\Entity\MyTable#0"。 - Jacek717
1
@Jacek717 抱歉,它是键/值对'id'=>'DESC',请查看更新的答案。 - M Khalid Junaid
我想那个应该可以工作! 我没有收到任何错误。 但是我仍然在从$results数组中获取数据方面遇到问题。 我的意思是,当我尝试输入类似于$output->writeln($results[0]);时,我会收到错误:“PHP Notice:Undefined offset:0”。 我在PHP / Symfony方面有点新手,所以也许这是一个非常愚蠢的问题,但我不知道如何从此变量中获取信息。 你能帮忙吗? - Jacek717
@Jacek717 如果您 dump $results,您会看到什么? - M Khalid Junaid
2
好的,我找到了问题所在。我将限制参数从0更改为1,现在一切都正常工作了。非常感谢您的帮助! - Jacek717
稍微有点细微的差别,你将0作为限制值,1作为偏移量传递了进去,你更应该使用$results = $repository->findBy(array(),array('id'=>'DESC'),1,0);来反转它。 - Steven Rosato

11

与其在需要时直接篡改代码,您也可以创建一个存储库方法,并在必要时调用它。

/**
 * 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();
}

参考文献: https://symfony.com/doc/current/doctrine.html#querying-for-objects-the-repository


1
替换ide.id似乎是必要的。 - Baudev
虽然 @M Khalid Junaid 提供的答案很简单,但是 @user3932886 发布的答案具有更好的可重用性,并且允许您的存储库/查询逻辑保持在一个地方,即存储库类内部,因此在大多数情况下应该优先考虑使用它。 - Ali

4

在寻找一个解决方案之后,我决定自己尝试一下。我认为这种方式简洁明了很多:

$myRepository->findOneBy([], ['id' => 'DESC']);

3

1
我使用了你的方法,但是出现了这个错误:"Undefined method 'orderBy'. The method must star with either findBy or findOneBy!" - Jacek717

1
您可以将这些功能添加到您的代码库中:

public function getLastRow(): ?YourEntity
{
    return $this->findOneBy([], ['id' => 'DESC']);
}

public function getLastId(): int
{
    $lastRow = $this->getLastRow();
    return $lastRow ? $lastRow->getId() : 0;
}

0

通过获取插入对象的id,您可以进行收集。

$em->persist($entity);
$em->flush();
$entity->getId();

或者

$entitymanager->getRepository("entity")->findBy([],["id"=>desc])->getId();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接