环境:
CakePHP 3
Postgres的
我尝试迁移以添加新字段,然后在Postgres数据库中更新该字段的某些数据。该实体似乎表明它已更新,但当我查看数据库时,它不会被保存。
代码
<?php
use Cake\Cache\Cache;
use Cake\ORM\TableRegistry;
use Migrations\AbstractMigration;
class AddDisplayRouteNumberToAgencies extends AbstractMigration
{
/**
* Up Method.
*/
public function up()
{
$table = $this->table('agencies');
$table->addColumn('display_route_number', 'boolean', [
'default' => true,
'null' => false,
]);
$table->update();
// Try to clear the Model cache
Cache::clear(null, '_cake_model_');
$patchData = [
'display_route_number' => false
];
$agencies = TableRegistry::get('Agencies');
$agency = $agencies->get(25);
// And save it back to the DB
$agencies->patchEntity($agency, $patchData);
debug($agency);
// Added after comment from ndm
$agencies->save($agency);
}
/**
* Down method
*/
public function down()
{
$table = $this->table('agencies');
$table->removeColumn('display_route_number');
$table->update();
// Clear the CakePHP Model cache
Cache::clear(null, '_cake_model_');
}
}
debug()
object(App\Model\Entity\Agency) {
'id' => (int) 25,
'full_name' => 'Agency',
'legacy_agency_slug' => null,
'created' => object(Cake\I18n\Time) {
'time' => '2015-11-19T10:58:51+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'modified' => object(Cake\I18n\Time) {
'time' => '2015-11-19T10:58:51+0000',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'display_route_number' => false,
'[new]' => false,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
'display_route_number' => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[repository]' => 'Agencies'
}
Postgres查询和结果
SELECT id, display_route_number
FROM agencies
WHERE id = 25;
id | display_route_number
----+----------------------
25 | t
(1 row)
我还尝试使用save()
而不是patchEntities()
,它返回了相同的结果,但[dirty]
为空。
$agencies = TableRegistry::get('Agencies');
$agency = $agencies->get(25);
// Items to update
$agency->display_route_number = false;
// And save it back to the DB
$agencies->save($agency);
答案 0 :(得分:0)
感谢@ndm为我解决这个问题。我最终不得不更新表架构。我相信这是因为Migration表部分更新了SQL,但没有更新Schema。
这是最终的代码:
// Clear the CakePHP Model cache
Cache::clear(null, '_cake_model_');
$table = $this->table('agencies');
$table->addColumn('display_route_number', 'boolean', [
'default' => true,
'null' => false,
]);
$table->update();
$agencies = TableRegistry::get('Agencies');
// REQUIRED!! Add the field to the Table schema
$agencies->schema()->addColumn('display_route_number', [
'type' => 'boolean',
'default' => true,
'null' => false
]);
$agency = $agencies->find()
->where(['short_name' => 'bart'])
->first();
// Items to update
$agency->display_route_number = false;
// And save it back to the DB
$agencies->save($agency);