EloquentMorphLazyEagerLoadingTest.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database\EloquentMorphLazyEagerLoadingTest;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Support\Facades\Schema;
  6. use Illuminate\Tests\Integration\Database\DatabaseTestCase;
  7. class EloquentMorphLazyEagerLoadingTest extends DatabaseTestCase
  8. {
  9. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  10. {
  11. Schema::create('users', function (Blueprint $table) {
  12. $table->increments('id');
  13. });
  14. Schema::create('posts', function (Blueprint $table) {
  15. $table->increments('post_id');
  16. $table->unsignedInteger('user_id');
  17. });
  18. Schema::create('comments', function (Blueprint $table) {
  19. $table->increments('id');
  20. $table->string('commentable_type');
  21. $table->integer('commentable_id');
  22. });
  23. $user = User::create();
  24. $post = tap((new Post)->user()->associate($user))->save();
  25. (new Comment)->commentable()->associate($post)->save();
  26. }
  27. public function testLazyEagerLoading()
  28. {
  29. $comment = Comment::first();
  30. $comment->loadMorph('commentable', [
  31. Post::class => ['user'],
  32. ]);
  33. $this->assertTrue($comment->relationLoaded('commentable'));
  34. $this->assertTrue($comment->commentable->relationLoaded('user'));
  35. }
  36. }
  37. class Comment extends Model
  38. {
  39. public $timestamps = false;
  40. public function commentable()
  41. {
  42. return $this->morphTo();
  43. }
  44. }
  45. class Post extends Model
  46. {
  47. public $timestamps = false;
  48. protected $primaryKey = 'post_id';
  49. public function user()
  50. {
  51. return $this->belongsTo(User::class);
  52. }
  53. }
  54. class User extends Model
  55. {
  56. public $timestamps = false;
  57. }