Cakephp3事务查找查询

时间:2015-06-12 10:36:56

标签: mysql select transactions cakephp-3.0

在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-Log中得到这个:

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

1 个答案:

答案 0 :(得分:1)

由于它对我来说很好,我怀疑你在事务回调之外还有一个额外的查询,它也查找id = 2,因为查询是由你显示的{{1}生成的因为查询是惰性求值的,所以永远不会执行调用。

目前您刚刚创建了一个查询对象,为了实际执行它,您必须致电find()all()first(),等等。或者迭代它。

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

相关问题