From 6ff59e5eca911460c2c7854ed47574fd49837312 Mon Sep 17 00:00:00 2001 From: PovilasKorop Date: Tue, 9 Nov 2021 11:15:09 +0200 Subject: [PATCH] Last test - null on foreign key --- README.md | 8 +++++ app/Models/Country.php | 11 ++++++ app/Models/Visitor.php | 13 +++++++ ...21_11_09_090752_create_countries_table.php | 32 +++++++++++++++++ ...021_11_09_090858_create_visitors_table.php | 34 +++++++++++++++++++ tests/Feature/MigrationsTest.php | 9 +++++ 6 files changed, 107 insertions(+) create mode 100644 app/Models/Country.php create mode 100644 app/Models/Visitor.php create mode 100644 database/migrations/task10/2021_11_09_090752_create_countries_table.php create mode 100644 database/migrations/task10/2021_11_09_090858_create_visitors_table.php diff --git a/README.md b/README.md index 72a597f..9363f88 100644 --- a/README.md +++ b/README.md @@ -111,3 +111,11 @@ Test method `test_renamed_column()`. --- +## Task 10. NULL on Foreign Key + +Folder `database/migrations/task10` contains migrations for countries and visitors table. Visitor may have undetected country, so country_id may be NULL. Change the visitors table migration to allow that. + +Test method `test_null_foreign_key()`. + +--- + diff --git a/app/Models/Country.php b/app/Models/Country.php new file mode 100644 index 0000000..fc698f5 --- /dev/null +++ b/app/Models/Country.php @@ -0,0 +1,11 @@ +id(); + $table->string('name'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('countries'); + } +} diff --git a/database/migrations/task10/2021_11_09_090858_create_visitors_table.php b/database/migrations/task10/2021_11_09_090858_create_visitors_table.php new file mode 100644 index 0000000..7a53968 --- /dev/null +++ b/database/migrations/task10/2021_11_09_090858_create_visitors_table.php @@ -0,0 +1,34 @@ +id(); + $table->foreignId('country_id')->constrained(); + $table->string('ip_address'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('visitors'); + } +} diff --git a/tests/Feature/MigrationsTest.php b/tests/Feature/MigrationsTest.php index 1499022..538ef40 100644 --- a/tests/Feature/MigrationsTest.php +++ b/tests/Feature/MigrationsTest.php @@ -7,6 +7,7 @@ use App\Models\Company; use App\Models\Product; use App\Models\Project; use App\Models\User; +use App\Models\Visitor; use Illuminate\Database\QueryException; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\DB; @@ -112,4 +113,12 @@ class MigrationsTest extends TestCase Company::create(['name' => 'First']); $this->assertDatabaseHas(Company::class, ['name' => 'First']); } + + public function test_null_foreign_key() + { + Artisan::call('migrate:fresh', ['--path' => '/database/migrations/task10']); + + Visitor::create(['ip_address' => '127.0.0.1']); + $this->assertDatabaseCount(Visitor::class, 1); + } }