PrimaryKeyBehavior.php 1021 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace common\behaviors;
  3. use common\helpers\snowflake\SnowFake;
  4. use yii\behaviors\AttributeBehavior;
  5. use yii\db\Expression;
  6. /**
  7. * Created by PhpStorm.
  8. * User: congli
  9. * Date: 2020/2/25
  10. * Time: 5:11 PM
  11. */
  12. class PrimaryKeyBehavior extends AttributeBehavior
  13. {
  14. public $primaryKeyAttribute = 'ID';
  15. public $value;
  16. public function init()
  17. {
  18. parent::init();
  19. if (empty($this->attributes)) {
  20. $this->attributes = [
  21. \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => [$this->primaryKeyAttribute],
  22. ];
  23. }
  24. }
  25. /**
  26. * @param \yii\base\Event $event
  27. * @return mixed
  28. */
  29. protected function getValue($event)
  30. {
  31. //@todo 修正同一事务中取ID会出错的问题
  32. // return new Expression("REPLACE(UUID(),'-','')");
  33. // $uuidStr = \Yii::$app->db->createCommand('select UUID()')->queryScalar();
  34. // return str_replace('-', '', $uuidStr);
  35. return SnowFake::instance()->generateId();
  36. }
  37. }