EloquentMorphToLazyEagerLoadingTest.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database\EloquentMorphToLazyEagerLoadingTest;
  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 EloquentMorphToLazyEagerLoadingTest extends DatabaseTestCase
  9. {
  10. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  11. {
  12. Schema::create('users', function (Blueprint $table) {
  13. $table->increments('id');
  14. });
  15. Schema::create('posts', function (Blueprint $table) {
  16. $table->increments('post_id');
  17. $table->unsignedInteger('user_id');
  18. });
  19. Schema::create('videos', function (Blueprint $table) {
  20. $table->increments('video_id');
  21. });
  22. Schema::create('comments', function (Blueprint $table) {
  23. $table->increments('id');
  24. $table->string('commentable_type');
  25. $table->integer('commentable_id');
  26. });
  27. $user = User::create();
  28. $post = tap((new Post)->user()->associate($user))->save();
  29. $video = Video::create();
  30. (new Comment)->commentable()->associate($post)->save();
  31. (new Comment)->commentable()->associate($video)->save();
  32. }
  33. public function testLazyEagerLoading()
  34. {
  35. $comments = Comment::all();
  36. DB::enableQueryLog();
  37. $comments->load('commentable');
  38. $this->assertCount(3, DB::getQueryLog());
  39. $this->assertTrue($comments[0]->relationLoaded('commentable'));
  40. $this->assertTrue($comments[0]->commentable->relationLoaded('user'));
  41. $this->assertTrue($comments[1]->relationLoaded('commentable'));
  42. }
  43. }
  44. class Comment extends Model
  45. {
  46. public $timestamps = false;
  47. public function commentable()
  48. {
  49. return $this->morphTo();
  50. }
  51. }
  52. class Post extends Model
  53. {
  54. public $timestamps = false;
  55. protected $primaryKey = 'post_id';
  56. protected $with = ['user'];
  57. public function user()
  58. {
  59. return $this->belongsTo(User::class);
  60. }
  61. }
  62. class User extends Model
  63. {
  64. public $timestamps = false;
  65. }
  66. class Video extends Model
  67. {
  68. public $timestamps = false;
  69. protected $primaryKey = 'video_id';
  70. }