使用给定的 uuid 保存记录

问题描述 投票:0回答:1

我想使用给定的 uuid 在数据库中保存一堆静态记录,这是出于测试目的,以便在每个系统上应用程序都以完全相同的数据集启动。

当使用 SQL 插入时,这没有问题,但我想使用 CakePHP 方式(我为此使用迁移文件,但这并不重要)。

问题是我给cake一个这样的数据数组并保存它:

$data = [
    ['id' => '5cedf79a-e4b9-f235-3d4d-9fbeef41c7e8', 'name' => 'test'],
    ['id' => 'c2bf879c-072c-51a4-83d8-edbf2d97e07e', 'name' => 'test2']
];

$table = TableRegistry::get('My_Model');

$entities = $table->newEntities($data, [
        'accessibleFields' => ['*' => true],
        'validate' => false
    ]);

array_map([$table, 'save'], $entities );

一切都保存了,但我的所有项目都被赋予了不同的uuid,如果我在保存后调试记录,它会显示实体中的原始uuid

'new' => false,
'accessible' => [
    '*' => true
],    
'properties' => [
    'id' => '6b4524a8-4698-4297-84e5-5160f42f663b',
    'name' => 'test',
],
'dirty' => [],
'original' => [
    'id' => '5cedf79a-e4b9-f235-3d4d-9fbeef41c7e8'
],

那么为什么cake要为我生成一个新的uuid呢?以及如何预防

php cakephp cakephp-3.0 uuid
1个回答
2
投票

这不起作用,因为主键是在插入操作之前无条件生成的,请参阅

https://github.com/cakephp/cakephp/blob/3.0.0/src/ORM/Table.php#L1486-L1490

// ...

$id = (array)$this->_newId($primary) + $keys;
$primary = array_combine($primary, $id);
$filteredKeys = array_filter($primary, 'strlen');
$data = $filteredKeys + $data;

// ...

$statement = $this->query()->insert(array_keys($data))
  ->values($data)
  ->execute();

// ...

目前 UUID 类型是唯一实现生成 ID 的类型,因此提供自定义 ID 可以与其他类型一起使用。

您可以通过例如覆盖表中的

_newId()
方法以使其返回
null
来解决此问题,这实际上会导致现有主键不被覆盖。

protected function _newId($primary)
{
    // maybe add some conditional logic here
    // in case you don't want to be required
    // to always manually provide a primary
    // key for your insert operations

    return null;
}
© www.soinside.com 2019 - 2024. All rights reserved.