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.
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
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.
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.
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".
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With