Fáze požadavku: 8. Databáze & Eloquent ORM
Modul 6 · Lekce 1

Databázové migrace v PostgreSQL: Tabulky, cizí klíče a JSONB sloupce

💡 Shrnutí lekce

Jak Laravel migrace definují databázové schéma pro PostgreSQL 18. Od cizích klíčů s kaskádovým mazáním přes optimalizované datové typy až po moderní JSONB sloupce.

Databázové migrace jako verzovací systém pro PostgreSQL

V moderním vývoji softwaru je nemyslitelné spravovat databázové tabulky ručními zásahy přes grafické rozhraní. Databázové schéma musí být verzováno v repozitáři stejně jako aplikační kód.

V Laravelu tuto úlohu plní Migrace (uložené v adresáři database/migrations/). Při nasazení na server stačí spustit příkaz php artisan migrate, který automaticky aplikuje všechny nové migrace.

V našem projektu běží nejnovější verze PostgreSQL 18 (v Docker kontejneru). Podívejme se, jak je schéma naší vzdělávací platformy definováno v souboru database/migrations/0001_01_01_000010_create_course_tables.php.

1. Integrita dat a cizí klíče s kaskádovým mazáním

Základem relační databáze je integrita vztahů mezi tabulkami. V naší migraci vytváříme hierarchii course_modules → course_lessons → quiz_questions:

Schema::create('course_lessons', function (Blueprint $table): void {
    $table->id();
    $table->foreignId('course_module_id')->constrained('course_modules')->cascadeOnDelete();
    $table->unsignedSmallInteger('number');
    $table->string('slug')->unique();
    // ...
});

Co se zde odehrává uvnitř PostgreSQL?

  1. $table->foreignId('course_module_id') vytvoří sloupec typu BIGINT odpovídající primárnímu klíči id rodiče.
  2. ->constrained('course_modules') vytvoří skutečné databázové omezení cizího klíče (FOREIGN KEY CONSTRAINT). PostgreSQL odmítne vložit lekci, pokud zadaný modul neexistuje.
  3. ->cascadeOnDelete() přidá pravidlo ON DELETE CASCADE. Pokud je smazán modul, PostgreSQL na úrovni své databázové enginy automaticky a atomicky smaže všechny jeho lekce (a díky stejnému pravidlu v quiz_questions i všechny navazující kvízové otázky). V databázi tak nikdy nezůstanou sirotčí záznamy.

2. Efektivní datové typy a indexy

Laravel Blueprint nabízí širokou škálu typů optimalizovaných pro PostgreSQL:

  • $table->unsignedSmallInteger('number'): Pro čísla modulů a lekcí (1 až 10) by byl klasický integer (4 bajty) nebo bigInteger (8 bajtů) zbytečným plýtváním. unsignedSmallInteger (2 bajty, SMALLINT) šetří místo na disku i v mezipaměti RAM.
  • $table->string('slug')->unique(): Vytváří unikátní B-Tree index na sloupci slug. Tento index je nezbytný pro bleskurychlé vyhledávání lekcí podle URL v Route Model Bindingu (O(log n) namísto pomalého full-table scanu O(n)).

3. Využití nativního typu JSON v PostgreSQL

V tabulkách course_lessons a student_profiles najdete sloupce:

$table->json('anatomy_files');
$table->json('completed_lessons');
$table->json('quiz_scores');

V PostgreSQL je JSON prvotřídním občanem. Oproti některým starším databázím, kde byl JSON pouze obyčejným textem, PostgreSQL validuje syntaktickou správnost JSON dokumentu a umožňuje v něm vyhledávat pomocí specializovaných JSON operátorů (->, ->>, @>).

4. Konfigurace spojení v config/database.php

V konfiguračním souboru config/database.php najdete nastavení ovladače 'pgsql':

  • 'search_path' => 'public': Určuje výchozí PostgreSQL schéma.
  • 'sslmode' => env('DB_SSLMODE', 'prefer'): Umožňuje bezpečné šifrované spojení s databází v produkčním prostředí Hetzneru.
💻 Klíčová konstrukce z praxe
// database/migrations/0001_01_01_000010_create_course_tables.php

Schema::create('course_lessons', function (Blueprint $table): void {
    $table->id();
    // Vytvoří cizí klíč s automatickým kaskádovým mazáním v PostgreSQL
    $table->foreignId('course_module_id')->constrained('course_modules')->cascadeOnDelete();
    $table->unsignedSmallInteger('number');
    $table->string('slug')->unique(); // B-Tree unikátní index pro Route Model Binding
    $table->string('title');
    $table->text('summary');
    $table->longText('content_markdown');
    $table->longText('code_snippet')->nullable();
    $table->json('anatomy_files'); // PostgreSQL JSON datový typ
    $table->text('anatomy_note')->nullable();
    $table->string('lifecycle_phase')->default('controller');
    $table->timestamps();
});

Schema::create('quiz_questions', function (Blueprint $table): void {
    $table->id();
    $table->foreignId('course_lesson_id')->constrained('course_lessons')->cascadeOnDelete();
    $table->unsignedSmallInteger('position')->default(1);
    $table->text('question');
    $table->json('options'); // Pole 4 možností v JSON formátu
    $table->unsignedSmallInteger('correct_option');
    $table->text('explanation');
    $table->timestamps();
});

🎯 Ověření znalostí z lekce

Kvíz otestuje pochopení architektury a reálného kódu probíraného v této lekci.

Otázka 1 z 3

Co přesně zajistí deklarace ->cascadeOnDelete() u cizího klíče v migraci pro PostgreSQL?

Otázka 2 z 3

Proč je u sloupce slug v tabulce course_lessons použita metoda ->unique()?

Otázka 3 z 3

Kde Laravel eviduje, které migrační soubory již byly v databázi spuštěny?

Zodpovězeno: 0 / 3
🔬 Živá anatomie v této aplikaci
2 soubory
Na co se v kódu zaměřit: V souboru database/migrations/0001_01_01_000010_create_course_tables.php si prohlédněte řádky 27–51. Všimněte si definice cascadeOnDelete() a sloupců typu json(). V config/database.php se podívejte na řádky 89–102 s nastavením pgsql připojení pro PostgreSQL.
cesta: database/migrations/0001_01_01_000010_create_course_tables.php
74 řádků · 2.6 KB
Migrační schéma pro moduly, lekce, kvízové otázky a anonymní profily studentů v PostgreSQL 18.
1 <?php
2
3 declare(strict_types=1);
4
5 use Illuminate\Database\Migrations\Migration;
6 use Illuminate\Database\Schema\Blueprint;
7 use Illuminate\Support\Facades\Schema;
8
9 return new class extends Migration
10 {
11 /**
12 * Run the migrations.
13 */
14 public function up(): void
15 {
16 Schema::create('course_modules', function (Blueprint $table): void {
17 $table->id();
18 $table->unsignedSmallInteger('number')->unique();
19 $table->string('slug')->unique();
20 $table->string('title');
21 $table->string('difficulty')->default('beginner');
22 $table->unsignedSmallInteger('estimated_minutes')->default(45);
23 $table->text('summary');
24 $table->timestamps();
25 });
26
27 Schema::create('course_lessons', function (Blueprint $table): void {
28 $table->id();
29 $table->foreignId('course_module_id')->constrained('course_modules')->cascadeOnDelete();
30 $table->unsignedSmallInteger('number');
31 $table->string('slug')->unique();
32 $table->string('title');
33 $table->text('summary');
34 $table->longText('content_markdown');
35 $table->longText('code_snippet')->nullable();
36 $table->json('anatomy_files');
37 $table->text('anatomy_note')->nullable();
38 $table->string('lifecycle_phase')->default('controller');
39 $table->timestamps();
40 });
41
42 Schema::create('quiz_questions', function (Blueprint $table): void {
43 $table->id();
44 $table->foreignId('course_lesson_id')->constrained('course_lessons')->cascadeOnDelete();
45 $table->unsignedSmallInteger('position')->default(1);
46 $table->text('question');
47 $table->json('options');
48 $table->unsignedSmallInteger('correct_option');
49 $table->text('explanation');
50 $table->timestamps();
51 });
52
53 Schema::create('student_profiles', function (Blueprint $table): void {
54 $table->id();
55 $table->uuid('token')->unique();
56 $table->string('transfer_code', 24)->unique();
57 $table->json('completed_lessons');
58 $table->json('quiz_scores');
59 $table->timestamp('last_active_at')->nullable();
60 $table->timestamps();
61 });
62 }
63
64 /**
65 * Reverse the migrations.
66 */
67 public function down(): void
68 {
69 Schema::dropIfExists('quiz_questions');
70 Schema::dropIfExists('course_lessons');
71 Schema::dropIfExists('course_modules');
72 Schema::dropIfExists('student_profiles');
73 }
74 };
75
cesta: config/database.php
186 řádků · 6.8 KB
Soubor aplikační architektury v modulu Configuration.
1 <?php
2
3 declare(strict_types=1);
4
5 use Illuminate\Support\Str;
6 use Pdo\Mysql;
7
8 return [
9
10 /*
11 |--------------------------------------------------------------------------
12 | Default Database Connection Name
13 |--------------------------------------------------------------------------
14 |
15 | Here you may specify which of the database connections below you wish
16 | to use as your default connection for database operations. This is
17 | the connection which will be utilized unless another connection
18 | is explicitly specified when you execute a query / statement.
19 |
20 */
21
22 'default' => env('DB_CONNECTION', 'sqlite'),
23
24 /*
25 |--------------------------------------------------------------------------
26 | Database Connections
27 |--------------------------------------------------------------------------
28 |
29 | Below are all of the database connections defined for your application.
30 | An example configuration is provided for each database system which
31 | is supported by Laravel. You're free to add / remove connections.
32 |
33 */
34
35 'connections' => [
36
37 'sqlite' => [
38 'driver' => 'sqlite',
39 'url' => env('DB_URL'),
40 'database' => env('DB_DATABASE', database_path('database.sqlite')),
41 'prefix' => '',
42 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
43 'busy_timeout' => null,
44 'journal_mode' => null,
45 'synchronous' => null,
46 'transaction_mode' => 'DEFERRED',
47 ],
48
49 'mysql' => [
50 'driver' => 'mysql',
51 'url' => env('DB_URL'),
52 'host' => env('DB_HOST', '127.0.0.1'),
53 'port' => env('DB_PORT', '3306'),
54 'database' => env('DB_DATABASE', 'laravel'),
55 'username' => env('DB_USERNAME', 'root'),
56 'password' => env('DB_PASSWORD', ''),
57 'unix_socket' => env('DB_SOCKET', ''),
58 'charset' => env('DB_CHARSET', 'utf8mb4'),
59 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
60 'prefix' => '',
61 'prefix_indexes' => true,
62 'strict' => true,
63 'engine' => null,
64 'options' => extension_loaded('pdo_mysql') ? array_filter([
65 (PHP_VERSION_ID >= 80500 ? Mysql::ATTR_SSL_CA : PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
66 ]) : [],
67 ],
68
69 'mariadb' => [
70 'driver' => 'mariadb',
71 'url' => env('DB_URL'),
72 'host' => env('DB_HOST', '127.0.0.1'),
73 'port' => env('DB_PORT', '3306'),
74 'database' => env('DB_DATABASE', 'laravel'),
75 'username' => env('DB_USERNAME', 'root'),
76 'password' => env('DB_PASSWORD', ''),
77 'unix_socket' => env('DB_SOCKET', ''),
78 'charset' => env('DB_CHARSET', 'utf8mb4'),
79 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
80 'prefix' => '',
81 'prefix_indexes' => true,
82 'strict' => true,
83 'engine' => null,
84 'options' => extension_loaded('pdo_mysql') ? array_filter([
85 (PHP_VERSION_ID >= 80500 ? Mysql::ATTR_SSL_CA : PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
86 ]) : [],
87 ],
88
89 'pgsql' => [
90 'driver' => 'pgsql',
91 'url' => env('DB_URL'),
92 'host' => env('DB_HOST', '127.0.0.1'),
93 'port' => env('DB_PORT', '5432'),
94 'database' => env('DB_DATABASE', 'laravel'),
95 'username' => env('DB_USERNAME', 'root'),
96 'password' => env('DB_PASSWORD', ''),
97 'charset' => env('DB_CHARSET', 'utf8'),
98 'prefix' => '',
99 'prefix_indexes' => true,
100 'search_path' => 'public',
101 'sslmode' => env('DB_SSLMODE', 'prefer'),
102 ],
103
104 'sqlsrv' => [
105 'driver' => 'sqlsrv',
106 'url' => env('DB_URL'),
107 'host' => env('DB_HOST', 'localhost'),
108 'port' => env('DB_PORT', '1433'),
109 'database' => env('DB_DATABASE', 'laravel'),
110 'username' => env('DB_USERNAME', 'root'),
111 'password' => env('DB_PASSWORD', ''),
112 'charset' => env('DB_CHARSET', 'utf8'),
113 'prefix' => '',
114 'prefix_indexes' => true,
115 // 'encrypt' => env('DB_ENCRYPT', 'yes'),
116 // 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
117 ],
118
119 ],
120
121 /*
122 |--------------------------------------------------------------------------
123 | Migration Repository Table
124 |--------------------------------------------------------------------------
125 |
126 | This table keeps track of all the migrations that have already run for
127 | your application. Using this information, we can determine which of
128 | the migrations on disk haven't actually been run on the database.
129 |
130 */
131
132 'migrations' => [
133 'table' => 'migrations',
134 'update_date_on_publish' => true,
135 ],
136
137 /*
138 |--------------------------------------------------------------------------
139 | Redis Databases
140 |--------------------------------------------------------------------------
141 |
142 | Redis is an open source, fast, and advanced key-value store that also
143 | provides a richer body of commands than a typical key-value system
144 | such as Memcached. You may define your connection settings here.
145 |
146 */
147
148 'redis' => [
149
150 'client' => env('REDIS_CLIENT', 'phpredis'),
151
152 'options' => [
153 'cluster' => env('REDIS_CLUSTER', 'redis'),
154 'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
155 'persistent' => env('REDIS_PERSISTENT', false),
156 ],
157
158 'default' => [
159 'url' => env('REDIS_URL'),
160 'host' => env('REDIS_HOST', '127.0.0.1'),
161 'username' => env('REDIS_USERNAME'),
162 'password' => env('REDIS_PASSWORD'),
163 'port' => env('REDIS_PORT', '6379'),
164 'database' => env('REDIS_DB', '0'),
165 'max_retries' => env('REDIS_MAX_RETRIES', 3),
166 'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
167 'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
168 'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
169 ],
170
171 'cache' => [
172 'url' => env('REDIS_URL'),
173 'host' => env('REDIS_HOST', '127.0.0.1'),
174 'username' => env('REDIS_USERNAME'),
175 'password' => env('REDIS_PASSWORD'),
176 'port' => env('REDIS_PORT', '6379'),
177 'database' => env('REDIS_CACHE_DB', '1'),
178 'max_retries' => env('REDIS_MAX_RETRIES', 3),
179 'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
180 'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
181 'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
182 ],
183
184 ],
185
186 ];
187
Zdroj: skutečné soubory této aplikace Plný průzkumník anatomie →