Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 - fetch the last inserted row from table

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.

like image 446
Jacek717 Avatar asked Jan 03 '18 06:01

Jacek717


People also ask

How do I find the last row in a table?

There is no such thing as the "last" row in a table, as an Oracle table has no concept of order. However, assuming that you wanted to find the last inserted primary key and that this primary key is an incrementing number, you could do something like this: select * from ( select a.*, max (pk) over () as max_pk from my_table a ) where pk = max_pk

Why can’t you call the last row the “last row”?

You could not because there is no "last row". You might have gotten the result you wanted (the highest value), but insisting on calling it the "last row" when it has been clearly explained that no such thing exists is not a good thing. . . Using proper terminology is as important as getting the answer you want.

How to get the first and last record in a table?

In order to introduce the concept of "first" and "last", you would need to specify how to order the rows which would require that there was one or more columns in the table that you could order by in order to determine the "last" record. if you have stored date of insertion or you have some incremental id column then it is possible only.

What is the last record in a DB2 table called?

there is no such a thing as a last record in a db2 table. the <things> are called rows. And there is no such thing as a "last row". Rows are rows. . . Using an ORDER BY and ascending or descending a query might return the highest or lowest value (s) from the found set, but these are neither "first" nor "last".


1 Answers

You could get the latest record by using findBy() with order by, limit and offset parameters

$results = $repository->findBy(array(),array('id'=>'DESC'),1,0);
  • 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

like image 82
M Khalid Junaid Avatar answered Sep 29 '22 23:09

M Khalid Junaid