EloquentModelLoadMissingTest.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database\EloquentModelLoadMissingTest;
  3. use DB;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Schema\Blueprint;
  6. use Illuminate\Support\Facades\Schema;
  7. use Illuminate\Tests\Integration\Database\DatabaseTestCase;
  8. class EloquentModelLoadMissingTest extends DatabaseTestCase
  9. {
  10. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  11. {
  12. Schema::create('posts', function (Blueprint $table) {
  13. $table->increments('id');
  14. });
  15. Schema::create('comments', function (Blueprint $table) {
  16. $table->increments('id');
  17. $table->unsignedInteger('parent_id')->nullable();
  18. $table->unsignedInteger('post_id');
  19. });
  20. Post::create();
  21. Comment::create(['parent_id' => null, 'post_id' => 1]);
  22. Comment::create(['parent_id' => 1, 'post_id' => 1]);
  23. }
  24. public function testLoadMissing()
  25. {
  26. $post = Post::with('comments')->first();
  27. DB::enableQueryLog();
  28. $post->loadMissing('comments.parent');
  29. $this->assertCount(1, DB::getQueryLog());
  30. $this->assertTrue($post->comments[0]->relationLoaded('parent'));
  31. }
  32. }
  33. class Comment extends Model
  34. {
  35. public $timestamps = false;
  36. protected $guarded = [];
  37. public function parent()
  38. {
  39. return $this->belongsTo(self::class);
  40. }
  41. }
  42. class Post extends Model
  43. {
  44. public $timestamps = false;
  45. public function comments()
  46. {
  47. return $this->hasMany(Comment::class);
  48. }
  49. }