Last test - null on foreign key

This commit is contained in:
PovilasKorop
2021-11-09 11:15:09 +02:00
parent 0140f00c32
commit 6ff59e5eca
6 changed files with 107 additions and 0 deletions
+8
View File
@@ -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()`.
---
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
use HasFactory;
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Visitor extends Model
{
use HasFactory;
protected $fillable = ['country_id', 'ip_address'];
}
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCountriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('countries', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('countries');
}
}
@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateVisitorsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// TASK: edit this migration so country_id would allow NULL values
Schema::create('visitors', function (Blueprint $table) {
$table->id();
$table->foreignId('country_id')->constrained();
$table->string('ip_address');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('visitors');
}
}
+9
View File
@@ -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);
}
}