CakePHP新手问题:如何复制模型及其相关数据?

发布于 2024-08-22 17:32:50 字数 106 浏览 2 评论 0原文

如何复制现有模型记录?换句话说,如何检索具有相关数据的现有模型,然后保存该模型和数据的副本(模型和相关数据都被复制)?使用简单的 SQL 这很简单,但我想使用 CakePHP 最佳实践来做到这一点。

How do I duplicate an existing model record? Put another way, how do I retrieve an existing model with related data, then save a COPY of that model AND data (both model and related data are copied)? This is trivial using simple SQL, but I want to do it using CakePHP best practices.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帅冕 2024-08-29 17:32:50
$record = $this->Model->find('first', array('condition' => array('Model.id' => $id)));
unset($record['Model']['id'], $record['RelatedModel']['id'], /* further ids */);
$this->Model->create();
$this->Model->saveAll($record);

基本上,您需要确保数据中不包含 id 字段,然后照常保存即可。这将提示 Cake 创建一条新记录。

根据您的具体数据,直接使用 $Model->query() 编写 INSERT … SELECT … 查询可能更经济。

$record = $this->Model->find('first', array('condition' => array('Model.id' => $id)));
unset($record['Model']['id'], $record['RelatedModel']['id'], /* further ids */);
$this->Model->create();
$this->Model->saveAll($record);

Basically, you'll want to make sure there are no id fields included in the data, then just save it as usual. That will prompt Cake to create a new record.

Depending on your specific data, it may be more economic to write an INSERT … SELECT … query directly using $Model->query() though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文