EloquentMorphConstrainTest.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database\EloquentMorphConstrainTest;
  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 EloquentMorphConstrainTest extends DatabaseTestCase
  9. {
  10. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  11. {
  12. Schema::create('posts', function (Blueprint $table) {
  13. $table->increments('id');
  14. $table->boolean('post_visible');
  15. });
  16. Schema::create('videos', function (Blueprint $table) {
  17. $table->increments('id');
  18. $table->boolean('video_visible');
  19. });
  20. Schema::create('comments', function (Blueprint $table) {
  21. $table->increments('id');
  22. $table->string('commentable_type');
  23. $table->integer('commentable_id');
  24. });
  25. $post1 = Post::create(['post_visible' => true]);
  26. (new Comment)->commentable()->associate($post1)->save();
  27. $post2 = Post::create(['post_visible' => false]);
  28. (new Comment)->commentable()->associate($post2)->save();
  29. $video1 = Video::create(['video_visible' => true]);
  30. (new Comment)->commentable()->associate($video1)->save();
  31. $video2 = Video::create(['video_visible' => false]);
  32. (new Comment)->commentable()->associate($video2)->save();
  33. }
  34. public function testMorphConstraints()
  35. {
  36. $comments = Comment::query()
  37. ->with(['commentable' => function (MorphTo $morphTo) {
  38. $morphTo->constrain([
  39. Post::class => function ($query) {
  40. $query->where('post_visible', true);
  41. },
  42. Video::class => function ($query) {
  43. $query->where('video_visible', true);
  44. },
  45. ]);
  46. }])
  47. ->get();
  48. $this->assertTrue($comments[0]->commentable->post_visible);
  49. $this->assertNull($comments[1]->commentable);
  50. $this->assertTrue($comments[2]->commentable->video_visible);
  51. $this->assertNull($comments[3]->commentable);
  52. }
  53. }
  54. class Comment extends Model
  55. {
  56. public $timestamps = false;
  57. public function commentable()
  58. {
  59. return $this->morphTo();
  60. }
  61. }
  62. class Post extends Model
  63. {
  64. public $timestamps = false;
  65. protected $fillable = ['post_visible'];
  66. protected $casts = ['post_visible' => 'boolean'];
  67. }
  68. class Video extends Model
  69. {
  70. public $timestamps = false;
  71. protected $fillable = ['video_visible'];
  72. protected $casts = ['video_visible' => 'boolean'];
  73. }