Skip to content

Instantly share code, notes, and snippets.

@ismail1432
Last active November 20, 2022 16:28
Show Gist options
  • Save ismail1432/9f72449f034a0562eeaa237e648c5a90 to your computer and use it in GitHub Desktop.
Save ismail1432/9f72449f034a0562eeaa237e648c5a90 to your computer and use it in GitHub Desktop.

Add a new column not null

We want to add the column age NOT NULL in the table user

Version 1.1

💡 Add the column nullable and write in with the code

💡 Make the property and the getter nullable

 // Model
class User
{
+  /**
+   * @ORM\Column(type="int", nullable=true)
+   */
+  private ?string $age = null; 
+  public setAge(int $age){};
+  public getName(): ?int {};
+ }

// SQL Migration  
+ ALTER TABLE user ADD age int DEFAULT NULL

Version 1.2

💡 Update all nullable rows, make the column not NULL

💡 Make the property and the getter not null

 // Model
class User
{
  /**
-   * @ORM\Column(type="int", nullable=true)  
+   * @ORM\Column(type="int", nullable=false)
+   */
-  private ?string $age = null; 
+  private string $age; 
   public setAge(int $age){};
-  public getAge(): ?int {};   
+  public getAge(): int {};
}

// SQL Migration
+ UPDATE user set age = 18 WHERE age IS NULL; // populate empty rows with your strategy
+ ALTER TABLE user ALTER age SET NOT NULL
@Spomky
Copy link

Spomky commented Nov 20, 2022

You mean getAge() instead of getName() right?

@ismail1432
Copy link
Author

YES! Thanks for the catch 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment