【问题标题】:Cakephp3 transaction find queryCakephp3 事务查找查询
【发布时间】:2015-06-12 10:36:55
【问题描述】:

在 cakephp3 中进行事务并在其中添加 get() 查询时一切正常。但是为什么在事务内部没有执行 find() 查询呢?

我在 cakephp3 中有以下控制器:

<?php 
namespace App\Controller;

use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;

use Cake\Network\Session;
use Cake\Event\Event;

use Cake\Network\Http\Client;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;

class DashboardController extends AppController {
        public function index(){
            $conn = ConnectionManager::get('default');

            $testModel = TableRegistry::get('Tests');

            $select1=array();
            $select2 = array();
            $saved = array();
            $conn->transactional(function ($connection)use(&$testModel,&$select1,&$select2,&$saved) {
                $select1 = $testModel->find('all')->where(['id' => 2]); // article with id 12

                $select2 = $testModel->get(1);
                $select2->content = 'foo';
                $saved = $testModel->save($select2);
            });
        }

    }
 ?>

我希望在 SQL 日志中得到这个:

BEGIN
SELECT Tests.id AS `Tests__id`, Tests.content AS `Tests__content` FROM tests Tests WHERE id = 2
SELECT Tests.id AS `Tests__id`, Tests.content AS `Tests__content` FROM tests Tests WHERE Tests.id = 1 LIMIT 1
UPDATE tests SET content = 'foo' WHERE id = 1
COMMIT

但是我得到了:

BEGIN
SELECT Tests.id AS `Tests__id`, Tests.content AS `Tests__content` FROM tests Tests WHERE Tests.id = 1 LIMIT 1
UPDATE tests SET content = 'foo' WHERE id = 1
COMMIT
SELECT Tests.id AS `Tests__id`, Tests.content AS `Tests__content` FROM tests Tests WHERE id = 2

【问题讨论】:

    标签: mysql select transactions cakephp-3.0


    【解决方案1】:

    由于它对我来说工作正常,我怀疑您在事务回调之外还有一个额外的查询,它也寻找 id = 2,因为您显示的 find() 调用生成的查询将永远不会被执行,因为查询是惰性求值的。

    现在您刚刚创建了一个查询对象,为了实际执行它,您必须调用all()first()toArray() 等,或者对其进行迭代。

    另请参阅Cookbook > ...ORM > Query Builder > How Are Queries Lazily Evaluated

    【讨论】:

    • 太棒了,谢谢!延迟加载是关键字。查询在事务之后执行,因为我在那里访问查询的结果。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多