EloquentMorphManyTest.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database\EloquentMorphManyTest;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Support\Carbon;
  6. use Illuminate\Support\Facades\Schema;
  7. use Illuminate\Support\Str;
  8. use Illuminate\Tests\Integration\Database\DatabaseTestCase;
  9. class EloquentMorphManyTest extends DatabaseTestCase
  10. {
  11. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  12. {
  13. Schema::create('posts', function (Blueprint $table) {
  14. $table->increments('id');
  15. $table->string('title');
  16. $table->timestamps();
  17. });
  18. Schema::create('comments', function (Blueprint $table) {
  19. $table->increments('id');
  20. $table->string('name');
  21. $table->integer('commentable_id');
  22. $table->string('commentable_type');
  23. $table->timestamps();
  24. });
  25. Carbon::setTestNow(null);
  26. }
  27. public function testUpdateModelWithDefaultWithCount()
  28. {
  29. $post = Post::create(['title' => Str::random()]);
  30. $post->update(['title' => 'new name']);
  31. $this->assertSame('new name', $post->title);
  32. }
  33. public function test_self_referencing_existence_query()
  34. {
  35. $post = Post::create(['title' => 'foo']);
  36. $comment = tap((new Comment(['name' => 'foo']))->commentable()->associate($post))->save();
  37. (new Comment(['name' => 'bar']))->commentable()->associate($comment)->save();
  38. $comments = Comment::has('replies')->get();
  39. $this->assertEquals([1], $comments->pluck('id')->all());
  40. }
  41. }
  42. class Post extends Model
  43. {
  44. public $table = 'posts';
  45. public $timestamps = true;
  46. protected $guarded = [];
  47. protected $withCount = ['comments'];
  48. public function comments()
  49. {
  50. return $this->morphMany(Comment::class, 'commentable');
  51. }
  52. }
  53. class Comment extends Model
  54. {
  55. public $table = 'comments';
  56. public $timestamps = true;
  57. protected $guarded = [];
  58. public function commentable()
  59. {
  60. return $this->morphTo();
  61. }
  62. public function replies()
  63. {
  64. return $this->morphMany(self::class, 'commentable');
  65. }
  66. }