快速查找数据库Cakephp中的最后一项
【腾讯云】亏本大甩卖,服务器4核16G 1年370元(带宽12M,系统盘120GB SSD盘,月流量2000GB)!!!!!!
云产品 配置 价格
服务器 1核2G,带宽5M,系统盘50GB SSD盘,月流量500GB 38元/年
MySQL 1核1G 19元/年
服务器 16核32G,带宽18M,系统盘250GB SSD盘,月流量5000GB 1197元/年
点我进入腾讯云,查看更多详情

I just inherited some cakePHP code and I am not very familiar with it (or any other php/serverside language). I need to set the id of the item I am adding to the database to be the value of the last item plus one, originally I did a call like this:

$id = $this->Project->find('count') + 1;

but this seems to add about 8 seconds to my page loading (which seems weird because the database only has about 400 items) but that is another problem. For now I need a faster way to find the id of the last item in the database, is there a way using find to quickly retrieve the last item in a given table?

#0

That's a very bad approach on setting the id.

You do know that, for example, MySQL supports auto-increment for INT-fields and therefore will set the id automatically for you?

The suggested functions getLastInsertId and getInsertId will only work after an insert and not always.

I also can't understand that your call adds 8 seconds to your siteload. If I do such a call on my table (which also has around 400 records) the call itself only needs a few milliseconds. There is no delay the user would notice.

I think there might be a problem with your database-setup as this seems very unlikely.

Also please have a look if your database supports auto-increment (I can't imagine that's not possible) as this would be the easiest way of adding your wanted functionality.

#1

I would try

$id = $this->Project->getLastInsertID();
$id++;

The method can be found in cake/libs/model/model.php in line 2768

As well as on this SO page

Cheers!

#2

If you are looking for the cakePHP3 solution to this you simply use last().

ie:

use Cake\ORM\TableRegistry;
....
$myrecordstable=Tableregistry::get('Myrecords');
$myrecords=$myrecordstable->find()->last();
$lastId = $myrecords->id;
....

推荐文章

在复杂目录结构中移动的Shell工具

在复杂目录结构中移动的Shell工具

推荐文章

写入SDCard文件失败,无一例外

写入SDCard文件失败,无一例外

推荐文章

成功返回局部变量的引用

成功返回局部变量的引用

推荐文章

C-is char*str中的字符串实际上等同于char str[]?

C-is char*str中的字符串实际上等同于char str[]?

推荐文章

Android:ContextMenu未显示

Android:ContextMenu未显示

推荐文章

php preg_match regex-match chars从a到z,应该包含@char

php preg_match regex-match chars从a到z,应该包含@char

推荐文章

如何覆盖调试.断言(在c中)并使其在没有visual studio的情况下工作

如何覆盖调试.断言(在c中)并使其在没有visual studio的情况下工作

推荐文章

由于相关产品状态未知,SQL Server 2008 R2 SMO引导程序安装失败

由于相关产品状态未知,SQL Server 2008 R2 SMO引导程序安装失败

推荐文章

为什么派生类不能引用基类?

为什么派生类不能引用基类?

推荐文章

如何设置外键?

如何设置外键?

推荐文章

差异:环境变量和注册表项

差异:环境变量和注册表项

推荐文章

含nHibernate的MVC3剃须刀

含nHibernate的MVC3剃须刀

推荐文章

我怎样才能使复选框更大?

我怎样才能使复选框更大?

推荐文章

为什么opencover不写入指定的输出文件?

为什么opencover不写入指定的输出文件?

推荐文章

https请求可缓存吗?

https请求可缓存吗?

推荐文章

如何动态加载存储在独立数据存储中的数据

如何动态加载存储在独立数据存储中的数据