EloquentMorphEagerLoadingTest.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database\EloquentMorphEagerLoadingTest;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\Relations\MorphTo;
  5. use Illuminate\Database\Schema\Blueprint;
  6. use Illuminate\Support\Facades\Schema;
  7. use Illuminate\Tests\Integration\Database\DatabaseTestCase;
  8. class EloquentMorphEagerLoadingTest 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 testWithMorphLoading()
  34. {
  35. $comments = Comment::query()
  36. ->with(['commentable' => function (MorphTo $morphTo) {
  37. $morphTo->morphWith([Post::class => ['user']]);
  38. }])
  39. ->get();
  40. $this->assertTrue($comments[0]->relationLoaded('commentable'));
  41. $this->assertTrue($comments[0]->commentable->relationLoaded('user'));
  42. $this->assertTrue($comments[1]->relationLoaded('commentable'));
  43. }
  44. public function testWithMorphLoadingWithSingleRelation()
  45. {
  46. $comments = Comment::query()
  47. ->with(['commentable' => function (MorphTo $morphTo) {
  48. $morphTo->morphWith([Post::class => 'user']);
  49. }])
  50. ->get();
  51. $this->assertTrue($comments[0]->relationLoaded('commentable'));
  52. $this->assertTrue($comments[0]->commentable->relationLoaded('user'));
  53. }
  54. }
  55. class Comment extends Model
  56. {
  57. public $timestamps = false;
  58. public function commentable()
  59. {
  60. return $this->morphTo();
  61. }
  62. }
  63. class Post extends Model
  64. {
  65. public $timestamps = false;
  66. protected $primaryKey = 'post_id';
  67. public function user()
  68. {
  69. return $this->belongsTo(User::class);
  70. }
  71. }
  72. class User extends Model
  73. {
  74. public $timestamps = false;
  75. }
  76. class Video extends Model
  77. {
  78. public $timestamps = false;
  79. protected $primaryKey = 'video_id';
  80. }