EloquentLazyEagerLoadingTest.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database\EloquentLazyEagerLoadingTest;
  3. use DB;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Schema\Blueprint;
  6. use Illuminate\Support\Facades\Schema;
  7. use Illuminate\Tests\Integration\Database\DatabaseTestCase;
  8. class EloquentLazyEagerLoadingTest extends DatabaseTestCase
  9. {
  10. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  11. {
  12. Schema::create('one', function (Blueprint $table) {
  13. $table->increments('id');
  14. });
  15. Schema::create('two', function (Blueprint $table) {
  16. $table->increments('id');
  17. $table->integer('one_id');
  18. });
  19. Schema::create('three', function (Blueprint $table) {
  20. $table->increments('id');
  21. $table->integer('one_id');
  22. });
  23. }
  24. public function testItBasic()
  25. {
  26. $one = Model1::create();
  27. $one->twos()->create();
  28. $one->threes()->create();
  29. $model = Model1::find($one->id);
  30. $this->assertTrue($model->relationLoaded('twos'));
  31. $this->assertFalse($model->relationLoaded('threes'));
  32. DB::enableQueryLog();
  33. $model->load('threes');
  34. $this->assertCount(1, DB::getQueryLog());
  35. $this->assertTrue($model->relationLoaded('threes'));
  36. }
  37. }
  38. class Model1 extends Model
  39. {
  40. public $table = 'one';
  41. public $timestamps = false;
  42. protected $guarded = [];
  43. protected $with = ['twos'];
  44. public function twos()
  45. {
  46. return $this->hasMany(Model2::class, 'one_id');
  47. }
  48. public function threes()
  49. {
  50. return $this->hasMany(Model3::class, 'one_id');
  51. }
  52. }
  53. class Model2 extends Model
  54. {
  55. public $table = 'two';
  56. public $timestamps = false;
  57. protected $guarded = [];
  58. public function one()
  59. {
  60. return $this->belongsTo(Model1::class, 'one_id');
  61. }
  62. }
  63. class Model3 extends Model
  64. {
  65. public $table = 'three';
  66. public $timestamps = false;
  67. protected $guarded = [];
  68. public function one()
  69. {
  70. return $this->belongsTo(Model1::class, 'one_id');
  71. }
  72. }