EloquentModelTest.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Support\Carbon;
  6. use Illuminate\Support\Facades\Schema;
  7. use Illuminate\Support\Str;
  8. class EloquentModelTest extends DatabaseTestCase
  9. {
  10. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  11. {
  12. Schema::create('test_model1', function (Blueprint $table) {
  13. $table->increments('id');
  14. $table->timestamp('nullable_date')->nullable();
  15. });
  16. Schema::create('test_model2', function (Blueprint $table) {
  17. $table->increments('id');
  18. $table->string('name');
  19. $table->string('title');
  20. });
  21. }
  22. public function testUserCanUpdateNullableDate()
  23. {
  24. $user = TestModel1::create([
  25. 'nullable_date' => null,
  26. ]);
  27. $user->fill([
  28. 'nullable_date' => $now = Carbon::now(),
  29. ]);
  30. $this->assertTrue($user->isDirty('nullable_date'));
  31. $user->save();
  32. $this->assertEquals($now->toDateString(), $user->nullable_date->toDateString());
  33. }
  34. public function testAttributeChanges()
  35. {
  36. $user = TestModel2::create([
  37. 'name' => Str::random(), 'title' => Str::random(),
  38. ]);
  39. $this->assertEmpty($user->getDirty());
  40. $this->assertEmpty($user->getChanges());
  41. $this->assertFalse($user->isDirty());
  42. $this->assertFalse($user->wasChanged());
  43. $user->name = $name = Str::random();
  44. $this->assertEquals(['name' => $name], $user->getDirty());
  45. $this->assertEmpty($user->getChanges());
  46. $this->assertTrue($user->isDirty());
  47. $this->assertFalse($user->wasChanged());
  48. $user->save();
  49. $this->assertEmpty($user->getDirty());
  50. $this->assertEquals(['name' => $name], $user->getChanges());
  51. $this->assertTrue($user->wasChanged());
  52. $this->assertTrue($user->wasChanged('name'));
  53. }
  54. }
  55. class TestModel1 extends Model
  56. {
  57. public $table = 'test_model1';
  58. public $timestamps = false;
  59. protected $guarded = [];
  60. protected $casts = ['nullable_date' => 'datetime'];
  61. }
  62. class TestModel2 extends Model
  63. {
  64. public $table = 'test_model2';
  65. public $timestamps = false;
  66. protected $guarded = [];
  67. }