EloquentMorphCountLazyEagerLoadingTest.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database\EloquentMorphCountLazyEagerLoadingTest;
  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 EloquentMorphCountLazyEagerLoadingTest extends DatabaseTestCase
  8. {
  9. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  10. {
  11. Schema::create('likes', function (Blueprint $table) {
  12. $table->increments('id');
  13. $table->unsignedInteger('post_id');
  14. });
  15. Schema::create('posts', function (Blueprint $table) {
  16. $table->increments('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. $post = Post::create();
  24. tap((new Like)->post()->associate($post))->save();
  25. tap((new Like)->post()->associate($post))->save();
  26. (new Comment)->commentable()->associate($post)->save();
  27. }
  28. public function testLazyEagerLoading()
  29. {
  30. $comment = Comment::first();
  31. $comment->loadMorphCount('commentable', [
  32. Post::class => ['likes'],
  33. ]);
  34. $this->assertTrue($comment->relationLoaded('commentable'));
  35. $this->assertEquals(2, $comment->commentable->likes_count);
  36. }
  37. }
  38. class Comment extends Model
  39. {
  40. public $timestamps = false;
  41. public function commentable()
  42. {
  43. return $this->morphTo();
  44. }
  45. }
  46. class Post extends Model
  47. {
  48. public $timestamps = false;
  49. public function likes()
  50. {
  51. return $this->hasMany(Like::class);
  52. }
  53. }
  54. class Like extends Model
  55. {
  56. public $timestamps = false;
  57. public function post()
  58. {
  59. return $this->belongsTo(Post::class);
  60. }
  61. }