2

Я пытаюсь применить следующую миграцию:Как сделать столбцы временной метки поддержки doctrine?

Schema::table('users', function (Blueprint $table) { 
    $table->timestamp('created_at')->useCurrent()->change(); 
}); 

Но artisan говорит:

[Doctrine\DBAL\DBALException] 
    Unknown column type "timestamp" requested. Any Doctrine type that you use has to be registered with \Doctrine\DBAL 
    \Types\Type::addType(). You can get a list of all the known types with \Doctrine\DBAL\Types\Type::getTypesMap(). I 
    f this error occurs during database introspection then you might have forgot to register all database types for a 
    Doctrine Type. Use AbstractPlatform#registerDoctrineTypeMapping() or have your custom types implement Type#getMapp 
    edDatabaseTypes(). If the type name is empty you might have a problem with the cache or forgot some mapping inform 
    ation. 

Когда я пытаюсь установить mmerian/doctrine-timestamp (composer install mmerian/doctrine-timestamp), composer говорит:

[InvalidArgumentException] 
    Could not find package mmerian/doctrine-timestamp at any version for your minimum-stability (stable). Check the pa 
    ckage spelling or your minimum-stability 

Что я делаю?

UPD С composer require mmerian/doctrine-timestamp=dev-master, я был в состоянии установить пакет, а затем добавил Type::addType('timestamp', 'DoctrineTimestamp\DBAL\Types\Timestamp'); перед тем Schema::table заявление, но теперь у меня есть другая ошибка:

[Illuminate\Database\QueryException] 
    SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'created_at' (SQL: ALTER TABLE u 
    sers CHANGE created_at created_at INT DEFAULT 'CURRENT_TIMESTAMP' NOT NULL) 

UPD я снова проверил если он работает с mmerian/doctrine-timestamp, так как я добавил только первый из линий от Документов тогда (или документ был обновлен):

Type::addType('timestamp', 'DoctrineTimestamp\DBAL\Types\Timestamp');           
DB::getDoctrineConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('Timestamp', 'timestamp'); 

Но это тоже не помогает. Миграция завершается успешно, но определение столбца не изменяется.

+0

Пожалуйста, покажите ваш 'composer.json' – maximkou

+0

Вы можете вручную добавить https://github.com/mmerian/doctrine-timestamp/blob/ master/lib/DoctrineTimestamp/DBAL/Types/Timestamp.php для вашего проекта –

ответ

1

Как можно видеть, mmerian/doctrine-timestamp не решить проблему. Во-первых, после того, как this line$table->getColumns()['created_at'] является

class Doctrine\DBAL\Schema\Column#520 (16) { 
    protected $_type => class Doctrine\DBAL\Types\DateTimeType#504 (0) { } 
    protected $_length => NULL 
    protected $_precision => int(10) 
    protected $_scale => int(0) 
    protected $_unsigned => bool(false) 
    protected $_fixed => bool(false) 
    protected $_notnull => bool(true) 
    protected $_default => string(17) "CURRENT_TIMESTAMP" 
    protected $_autoincrement => bool(false) 
    protected $_platformOptions => array(0) { } 
    protected $_columnDefinition => NULL 
    protected $_comment => NULL 
    protected $_customSchemaOptions => array(0) { } 
    protected $_name => string(10) "created_at" 
    protected $_namespace => NULL 
    protected $_quoted => bool(false) 
} 

и $this->getTableWithColumnChanges($blueprint, $table)->getColumns()['created_at'] является

class Doctrine\DBAL\Schema\Column#533 (16) { 
    protected $_type => class DoctrineTimestamp\DBAL\Types\Timestamp#513 (0) { } 
    protected $_length => NULL 
    protected $_precision => int(10) 
    protected $_scale => int(0) 
    protected $_unsigned => bool(false) 
    protected $_fixed => bool(false) 
    protected $_notnull => bool(true) 
    protected $_default => string(17) "CURRENT_TIMESTAMP" 
    protected $_autoincrement => bool(false) 
    protected $_platformOptions => array(0) { } 
    protected $_columnDefinition => NULL 
    protected $_comment => NULL 
    protected $_customSchemaOptions => array(0) { } 
    protected $_name => string(10) "created_at" 
    protected $_namespace => NULL 
    protected $_quoted => bool(false) 
} 

Итак, сначала я не могу увидеть информацию о ON UPDATE часть здесь. Во-вторых, разница в товаре равна $_type. Что я могу подтвердить, после this line, $tableDiff->changedColumns['created_at']->changedProperties является

array(1) { 
    [0] => string(4) "type" 
} 

Затем, когда generatingALTER TABLEstatement, все сводится к этому

public function getDefaultValueDeclarationSQL($field) 
{ 
    $default = empty($field['notnull']) ? ' DEFAULT NULL' : ''; 
    if (isset($field['default'])) { 
     $default = " DEFAULT '".$field['default']."'"; 
     if (isset($field['type'])) { 
      if (in_array((string) $field['type'], array("Integer", "BigInt", "SmallInt"))) { 
       $default = " DEFAULT ".$field['default']; 
      } elseif (in_array((string) $field['type'], array('DateTime', 'DateTimeTz')) && $field['default'] == $this->getCurrentTimestampSQL()) { 
       $default = " DEFAULT ".$this->getCurrentTimestampSQL(); 
      } elseif ((string) $field['type'] == 'Time' && $field['default'] == $this->getCurrentTimeSQL()) { 
       $default = " DEFAULT ".$this->getCurrentTimeSQL(); 
      } elseif ((string) $field['type'] == 'Date' && $field['default'] == $this->getCurrentDateSQL()) { 
       $default = " DEFAULT ".$this->getCurrentDateSQL(); 
      } elseif ((string) $field['type'] == 'Boolean') { 
       $default = " DEFAULT '" . $this->convertBooleans($field['default']) . "'"; 
      } 
     } 
    } 
    return $default; 
} 

Где-то около this line там должен быть чек на Timestamp типа, чтобы включить 'CURRENT_TIMESTAMP' - CURRENT_TIMESTAMP. Возможно ли это в пределах mmerian/doctrine-timestamp? На данный момент этот вопрос остается открытым. Эта проверка, скорее всего, решит мою конкретную проблему.Но сейчас я собираюсь уйти с этим:

DB::statement('ALTER TABLE users MODIFY COLUMN created_at 
    TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'); 
0

Набор minimum-stability установка для dev в вашем composer.json, потому что mmerian/doctrine-timestamp имеет только dev-master версию, к примеру:

{ 
    "minimum-stability": "dev", 
    "require": { 
     ... 
    } 
} 

Then, when bootstraping your doctrine connection:

Type::addType('timestamp', 'DoctrineTimestamp\DBAL\Types\Timestamp'); 
$conn->getDatabasePlatform()->registerDoctrineTypeMapping('Timestamp', 'timestamp'); 
+0

Снижение минимальной стабильности [не рекомендуется] (https://igor.io/2013/02/07/composer-stability-flags.html). Запуск 'composer install mmerian/doctrine-timestamp = dev-master' делает трюк. –

+0

Добавление второй строки не помогло. –

0

Я построил this для него, так как доктрина не хочет, чтобы поддержать это может вызвать это MySQL-конкретный тип столбца.

+0

Это не работает для меня. Миграция завершается успешно, но определение столбцов остается неизменным: 'created_at timestamp NULL DEFAULT NULL'. –

+0

Что вы тоже пытаетесь изменить? –

+0

'ALTER TABLE users MODIFY COLUMN created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP', см. Мой ответ –

0

привет ~ Вы можете использовать тип "DATETIME":

Schema::table('orders', function ($table) { 

     $table->datetime('pay_time')->nullable()->change(); 

    }); 

 Смежные вопросы

  • Нет связанных вопросов^_^