EloquentMorphToGlobalScopesTest.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database\EloquentMorphToGlobalScopesTest;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\SoftDeletes;
  5. use Illuminate\Database\Eloquent\SoftDeletingScope;
  6. use Illuminate\Database\Schema\Blueprint;
  7. use Illuminate\Support\Facades\Schema;
  8. use Illuminate\Tests\Integration\Database\DatabaseTestCase;
  9. class EloquentMorphToGlobalScopesTest extends DatabaseTestCase
  10. {
  11. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  12. {
  13. Schema::create('posts', function (Blueprint $table) {
  14. $table->increments('id');
  15. $table->softDeletes();
  16. });
  17. Schema::create('comments', function (Blueprint $table) {
  18. $table->increments('id');
  19. $table->string('commentable_type');
  20. $table->integer('commentable_id');
  21. });
  22. $post = Post::create();
  23. (new Comment)->commentable()->associate($post)->save();
  24. $post = tap(Post::create())->delete();
  25. (new Comment)->commentable()->associate($post)->save();
  26. }
  27. public function testWithGlobalScopes()
  28. {
  29. $comments = Comment::with('commentable')->get();
  30. $this->assertNotNull($comments[0]->commentable);
  31. $this->assertNull($comments[1]->commentable);
  32. }
  33. public function testWithoutGlobalScope()
  34. {
  35. $comments = Comment::with(['commentable' => function ($query) {
  36. $query->withoutGlobalScopes([SoftDeletingScope::class]);
  37. }])->get();
  38. $this->assertNotNull($comments[0]->commentable);
  39. $this->assertNotNull($comments[1]->commentable);
  40. }
  41. public function testWithoutGlobalScopes()
  42. {
  43. $comments = Comment::with(['commentable' => function ($query) {
  44. $query->withoutGlobalScopes();
  45. }])->get();
  46. $this->assertNotNull($comments[0]->commentable);
  47. $this->assertNotNull($comments[1]->commentable);
  48. }
  49. public function testLazyLoading()
  50. {
  51. $comment = Comment::latest('id')->first();
  52. $post = $comment->commentable()->withoutGlobalScopes()->first();
  53. $this->assertNotNull($post);
  54. }
  55. }
  56. class Comment extends Model
  57. {
  58. public $timestamps = false;
  59. public function commentable()
  60. {
  61. return $this->morphTo();
  62. }
  63. }
  64. class Post extends Model
  65. {
  66. use SoftDeletes;
  67. public $timestamps = false;
  68. }