Skip to content

Instantly share code, notes, and snippets.

@ismail1432
Last active November 5, 2022 15:17
Show Gist options
  • Save ismail1432/0e6726b86ef408acb1d88d06e478e123 to your computer and use it in GitHub Desktop.
Save ismail1432/0e6726b86ef408acb1d88d06e478e123 to your computer and use it in GitHub Desktop.

Rename a column

We want to rename the column name to lastname in the table user

💡 The plan is to add a new column lastname, write in both from the codebase :bulb: Populate the new columns lastname with column name

Step 1

💡 Add the new column nullable 💡 Make the property nullable 💡 Make the column to rename nullable 💡 Replace older setter/getter by the setter/getter in the codebase

 // Model
class User
{
+  /**
+   * @ORM\Column(type="int", nullable=true)
+   */
+  private ?string $lastname = null; 
+  public setLastname(string $lastname){};
+  public getLastname(): string 
+  {
+    return $this->$lastname ?? $this->$name;   
+  }
-  public setName(string $name){};
-  public getName(): string {};
 }

// FooHandler.php
- $user->setName("Smaone");
+ $user->setLastname("Smaone");
- $user->getName();
+ $user->getLastname();


// SQL Migration  
+ ALTER TABLE user ADD lastname int DEFAULT NULL
+ ALTER TABLE user ALTER name drop NOT NULL

Step 2

💡 Update all null rows, make the column not NULL 💡 Make the property and the getter not null 💡 remove the old column

 // Model
class User
{
  /**
-   * @ORM\Column(type="int", nullable=true)  
+   * @ORM\Column(type="int", nullable=false)
+   */
-  private ?string $lastname = null; 
+  private string $lastname; 
   public setLastname(string $lastname){};
  public getLastname(): string 
  {
-   return $this->$lastname ?? $this->$name; 
+   return $this->$lastname;  
  }
}

// SQL Migration
+ UPDATE user set lastname = name WHERE lastname IS NULL;
+ ALTER TABLE user DROP name;
+ ALTER TABLE user ALTER lastname DROP NOT NULL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment