EloquentMorphToSelectTest.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database\EloquentMorphToSelectTest;
  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 EloquentMorphToSelectTest extends DatabaseTestCase
  8. {
  9. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  10. {
  11. Schema::create('posts', function (Blueprint $table) {
  12. $table->increments('id');
  13. $table->timestamps();
  14. });
  15. Schema::create('comments', function (Blueprint $table) {
  16. $table->increments('id');
  17. $table->string('commentable_type');
  18. $table->integer('commentable_id');
  19. });
  20. $post = Post::create();
  21. (new Comment)->commentable()->associate($post)->save();
  22. }
  23. public function testSelect()
  24. {
  25. $comments = Comment::with('commentable:id')->get();
  26. $this->assertEquals(['id' => 1], $comments[0]->commentable->getAttributes());
  27. }
  28. public function testSelectRaw()
  29. {
  30. $comments = Comment::with(['commentable' => function ($query) {
  31. $query->selectRaw('id');
  32. }])->get();
  33. $this->assertEquals(['id' => 1], $comments[0]->commentable->getAttributes());
  34. }
  35. public function testSelectSub()
  36. {
  37. $comments = Comment::with(['commentable' => function ($query) {
  38. $query->selectSub(function ($query) {
  39. $query->select('id');
  40. }, 'id');
  41. }])->get();
  42. $this->assertEquals(['id' => 1], $comments[0]->commentable->getAttributes());
  43. }
  44. public function testAddSelect()
  45. {
  46. $comments = Comment::with(['commentable' => function ($query) {
  47. $query->addSelect('id');
  48. }])->get();
  49. $this->assertEquals(['id' => 1], $comments[0]->commentable->getAttributes());
  50. }
  51. public function testLazyLoading()
  52. {
  53. $comment = Comment::first();
  54. $post = $comment->commentable()->select('id')->first();
  55. $this->assertEquals(['id' => 1], $post->getAttributes());
  56. }
  57. }
  58. class Comment extends Model
  59. {
  60. public $timestamps = false;
  61. public function commentable()
  62. {
  63. return $this->morphTo();
  64. }
  65. }
  66. class Post extends Model
  67. {
  68. //
  69. }