DatabaseEloquentHasManyThroughIntegrationTest.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. <?php
  2. namespace Illuminate\Tests\Database;
  3. use Illuminate\Database\Capsule\Manager as DB;
  4. use Illuminate\Database\Eloquent\Model as Eloquent;
  5. use Illuminate\Database\Eloquent\ModelNotFoundException;
  6. use Illuminate\Database\Eloquent\SoftDeletes;
  7. use Illuminate\Support\Collection;
  8. use Illuminate\Support\LazyCollection;
  9. use PHPUnit\Framework\TestCase;
  10. class DatabaseEloquentHasManyThroughIntegrationTest extends TestCase
  11. {
  12. protected function setUp(): void
  13. {
  14. $db = new DB;
  15. $db->addConnection([
  16. 'driver' => 'sqlite',
  17. 'database' => ':memory:',
  18. ]);
  19. $db->bootEloquent();
  20. $db->setAsGlobal();
  21. $this->createSchema();
  22. }
  23. /**
  24. * Setup the database schema.
  25. *
  26. * @return void
  27. */
  28. public function createSchema()
  29. {
  30. $this->schema()->create('users', function ($table) {
  31. $table->increments('id');
  32. $table->string('email')->unique();
  33. $table->unsignedInteger('country_id');
  34. $table->string('country_short');
  35. $table->timestamps();
  36. $table->softDeletes();
  37. });
  38. $this->schema()->create('posts', function ($table) {
  39. $table->increments('id');
  40. $table->integer('user_id');
  41. $table->string('title');
  42. $table->text('body');
  43. $table->string('email');
  44. $table->timestamps();
  45. });
  46. $this->schema()->create('countries', function ($table) {
  47. $table->increments('id');
  48. $table->string('name');
  49. $table->string('shortname');
  50. $table->timestamps();
  51. });
  52. }
  53. /**
  54. * Tear down the database schema.
  55. *
  56. * @return void
  57. */
  58. protected function tearDown(): void
  59. {
  60. $this->schema()->drop('users');
  61. $this->schema()->drop('posts');
  62. $this->schema()->drop('countries');
  63. }
  64. public function testItLoadsAHasManyThroughRelationWithCustomKeys()
  65. {
  66. $this->seedData();
  67. $posts = HasManyThroughTestCountry::first()->posts;
  68. $this->assertSame('A title', $posts[0]->title);
  69. $this->assertCount(2, $posts);
  70. }
  71. public function testItLoadsADefaultHasManyThroughRelation()
  72. {
  73. $this->migrateDefault();
  74. $this->seedDefaultData();
  75. $posts = HasManyThroughDefaultTestCountry::first()->posts;
  76. $this->assertSame('A title', $posts[0]->title);
  77. $this->assertCount(2, $posts);
  78. $this->resetDefault();
  79. }
  80. public function testItLoadsARelationWithCustomIntermediateAndLocalKey()
  81. {
  82. $this->seedData();
  83. $posts = HasManyThroughIntermediateTestCountry::first()->posts;
  84. $this->assertSame('A title', $posts[0]->title);
  85. $this->assertCount(2, $posts);
  86. }
  87. public function testEagerLoadingARelationWithCustomIntermediateAndLocalKey()
  88. {
  89. $this->seedData();
  90. $posts = HasManyThroughIntermediateTestCountry::with('posts')->first()->posts;
  91. $this->assertSame('A title', $posts[0]->title);
  92. $this->assertCount(2, $posts);
  93. }
  94. public function testWhereHasOnARelationWithCustomIntermediateAndLocalKey()
  95. {
  96. $this->seedData();
  97. $country = HasManyThroughIntermediateTestCountry::whereHas('posts', function ($query) {
  98. $query->where('title', 'A title');
  99. })->get();
  100. $this->assertCount(1, $country);
  101. }
  102. public function testFindMethod()
  103. {
  104. HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us'])
  105. ->users()->create(['id' => 1, 'email' => 'taylorotwell@gmail.com', 'country_short' => 'us'])
  106. ->posts()->createMany([
  107. ['id' => 1, 'title' => 'A title', 'body' => 'A body', 'email' => 'taylorotwell@gmail.com'],
  108. ['id' => 2, 'title' => 'Another title', 'body' => 'Another body', 'email' => 'taylorotwell@gmail.com'],
  109. ]);
  110. $country = HasManyThroughTestCountry::first();
  111. $post = $country->posts()->find(1);
  112. $this->assertNotNull($post);
  113. $this->assertSame('A title', $post->title);
  114. $this->assertCount(2, $country->posts()->find([1, 2]));
  115. $this->assertCount(2, $country->posts()->find(new Collection([1, 2])));
  116. }
  117. public function testFindManyMethod()
  118. {
  119. HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us'])
  120. ->users()->create(['id' => 1, 'email' => 'taylorotwell@gmail.com', 'country_short' => 'us'])
  121. ->posts()->createMany([
  122. ['id' => 1, 'title' => 'A title', 'body' => 'A body', 'email' => 'taylorotwell@gmail.com'],
  123. ['id' => 2, 'title' => 'Another title', 'body' => 'Another body', 'email' => 'taylorotwell@gmail.com'],
  124. ]);
  125. $country = HasManyThroughTestCountry::first();
  126. $this->assertCount(2, $country->posts()->findMany([1, 2]));
  127. $this->assertCount(2, $country->posts()->findMany(new Collection([1, 2])));
  128. }
  129. public function testFirstOrFailThrowsAnException()
  130. {
  131. $this->expectException(ModelNotFoundException::class);
  132. $this->expectExceptionMessage('No query results for model [Illuminate\Tests\Database\HasManyThroughTestPost].');
  133. HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us'])
  134. ->users()->create(['id' => 1, 'email' => 'taylorotwell@gmail.com', 'country_short' => 'us']);
  135. HasManyThroughTestCountry::first()->posts()->firstOrFail();
  136. }
  137. public function testFindOrFailThrowsAnException()
  138. {
  139. $this->expectException(ModelNotFoundException::class);
  140. $this->expectExceptionMessage('No query results for model [Illuminate\Tests\Database\HasManyThroughTestPost] 1');
  141. HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us'])
  142. ->users()->create(['id' => 1, 'email' => 'taylorotwell@gmail.com', 'country_short' => 'us']);
  143. HasManyThroughTestCountry::first()->posts()->findOrFail(1);
  144. }
  145. public function testFindOrFailWithManyThrowsAnException()
  146. {
  147. $this->expectException(ModelNotFoundException::class);
  148. $this->expectExceptionMessage('No query results for model [Illuminate\Tests\Database\HasManyThroughTestPost] 1, 2');
  149. HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us'])
  150. ->users()->create(['id' => 1, 'email' => 'taylorotwell@gmail.com', 'country_short' => 'us'])
  151. ->posts()->create(['id' => 1, 'title' => 'A title', 'body' => 'A body', 'email' => 'taylorotwell@gmail.com']);
  152. HasManyThroughTestCountry::first()->posts()->findOrFail([1, 2]);
  153. }
  154. public function testFindOrFailWithManyUsingCollectionThrowsAnException()
  155. {
  156. $this->expectException(ModelNotFoundException::class);
  157. $this->expectExceptionMessage('No query results for model [Illuminate\Tests\Database\HasManyThroughTestPost] 1, 2');
  158. HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us'])
  159. ->users()->create(['id' => 1, 'email' => 'taylorotwell@gmail.com', 'country_short' => 'us'])
  160. ->posts()->create(['id' => 1, 'title' => 'A title', 'body' => 'A body', 'email' => 'taylorotwell@gmail.com']);
  161. HasManyThroughTestCountry::first()->posts()->findOrFail(new Collection([1, 2]));
  162. }
  163. public function testFirstRetrievesFirstRecord()
  164. {
  165. $this->seedData();
  166. $post = HasManyThroughTestCountry::first()->posts()->first();
  167. $this->assertNotNull($post);
  168. $this->assertSame('A title', $post->title);
  169. }
  170. public function testAllColumnsAreRetrievedByDefault()
  171. {
  172. $this->seedData();
  173. $post = HasManyThroughTestCountry::first()->posts()->first();
  174. $this->assertEquals([
  175. 'id',
  176. 'user_id',
  177. 'title',
  178. 'body',
  179. 'email',
  180. 'created_at',
  181. 'updated_at',
  182. 'laravel_through_key',
  183. ], array_keys($post->getAttributes()));
  184. }
  185. public function testOnlyProperColumnsAreSelectedIfProvided()
  186. {
  187. $this->seedData();
  188. $post = HasManyThroughTestCountry::first()->posts()->first(['title', 'body']);
  189. $this->assertEquals([
  190. 'title',
  191. 'body',
  192. 'laravel_through_key',
  193. ], array_keys($post->getAttributes()));
  194. }
  195. public function testChunkReturnsCorrectModels()
  196. {
  197. $this->seedData();
  198. $this->seedDataExtended();
  199. $country = HasManyThroughTestCountry::find(2);
  200. $country->posts()->chunk(10, function ($postsChunk) {
  201. $post = $postsChunk->first();
  202. $this->assertEquals([
  203. 'id',
  204. 'user_id',
  205. 'title',
  206. 'body',
  207. 'email',
  208. 'created_at',
  209. 'updated_at',
  210. 'laravel_through_key',
  211. ], array_keys($post->getAttributes()));
  212. });
  213. }
  214. public function testChunkById()
  215. {
  216. $this->seedData();
  217. $this->seedDataExtended();
  218. $country = HasManyThroughTestCountry::find(2);
  219. $i = 0;
  220. $count = 0;
  221. $country->posts()->chunkById(2, function ($collection) use (&$i, &$count) {
  222. $i++;
  223. $count += $collection->count();
  224. });
  225. $this->assertEquals(3, $i);
  226. $this->assertEquals(6, $count);
  227. }
  228. public function testCursorReturnsCorrectModels()
  229. {
  230. $this->seedData();
  231. $this->seedDataExtended();
  232. $country = HasManyThroughTestCountry::find(2);
  233. $posts = $country->posts()->cursor();
  234. $this->assertInstanceOf(LazyCollection::class, $posts);
  235. foreach ($posts as $post) {
  236. $this->assertEquals([
  237. 'id',
  238. 'user_id',
  239. 'title',
  240. 'body',
  241. 'email',
  242. 'created_at',
  243. 'updated_at',
  244. 'laravel_through_key',
  245. ], array_keys($post->getAttributes()));
  246. }
  247. }
  248. public function testEachReturnsCorrectModels()
  249. {
  250. $this->seedData();
  251. $this->seedDataExtended();
  252. $country = HasManyThroughTestCountry::find(2);
  253. $country->posts()->each(function ($post) {
  254. $this->assertEquals([
  255. 'id',
  256. 'user_id',
  257. 'title',
  258. 'body',
  259. 'email',
  260. 'created_at',
  261. 'updated_at',
  262. 'laravel_through_key',
  263. ], array_keys($post->getAttributes()));
  264. });
  265. }
  266. public function testLazyReturnsCorrectModels()
  267. {
  268. $this->seedData();
  269. $this->seedDataExtended();
  270. $country = HasManyThroughTestCountry::find(2);
  271. $country->posts()->lazy(10)->each(function ($post) {
  272. $this->assertEquals([
  273. 'id',
  274. 'user_id',
  275. 'title',
  276. 'body',
  277. 'email',
  278. 'created_at',
  279. 'updated_at',
  280. 'laravel_through_key',
  281. ], array_keys($post->getAttributes()));
  282. });
  283. }
  284. public function testLazyById()
  285. {
  286. $this->seedData();
  287. $this->seedDataExtended();
  288. $country = HasManyThroughTestCountry::find(2);
  289. $i = 0;
  290. $country->posts()->lazyById(2)->each(function ($post) use (&$i, &$count) {
  291. $i++;
  292. $this->assertEquals([
  293. 'id',
  294. 'user_id',
  295. 'title',
  296. 'body',
  297. 'email',
  298. 'created_at',
  299. 'updated_at',
  300. 'laravel_through_key',
  301. ], array_keys($post->getAttributes()));
  302. });
  303. $this->assertEquals(6, $i);
  304. }
  305. public function testIntermediateSoftDeletesAreIgnored()
  306. {
  307. $this->seedData();
  308. HasManyThroughSoftDeletesTestUser::first()->delete();
  309. $posts = HasManyThroughSoftDeletesTestCountry::first()->posts;
  310. $this->assertSame('A title', $posts[0]->title);
  311. $this->assertCount(2, $posts);
  312. }
  313. public function testEagerLoadingLoadsRelatedModelsCorrectly()
  314. {
  315. $this->seedData();
  316. $country = HasManyThroughSoftDeletesTestCountry::with('posts')->first();
  317. $this->assertSame('us', $country->shortname);
  318. $this->assertSame('A title', $country->posts[0]->title);
  319. $this->assertCount(2, $country->posts);
  320. }
  321. /**
  322. * Helpers...
  323. */
  324. protected function seedData()
  325. {
  326. HasManyThroughTestCountry::create(['id' => 1, 'name' => 'United States of America', 'shortname' => 'us'])
  327. ->users()->create(['id' => 1, 'email' => 'taylorotwell@gmail.com', 'country_short' => 'us'])
  328. ->posts()->createMany([
  329. ['title' => 'A title', 'body' => 'A body', 'email' => 'taylorotwell@gmail.com'],
  330. ['title' => 'Another title', 'body' => 'Another body', 'email' => 'taylorotwell@gmail.com'],
  331. ]);
  332. }
  333. protected function seedDataExtended()
  334. {
  335. $country = HasManyThroughTestCountry::create(['id' => 2, 'name' => 'United Kingdom', 'shortname' => 'uk']);
  336. $country->users()->create(['id' => 2, 'email' => 'example1@gmail.com', 'country_short' => 'uk'])
  337. ->posts()->createMany([
  338. ['title' => 'Example1 title1', 'body' => 'Example1 body1', 'email' => 'example1post1@gmail.com'],
  339. ['title' => 'Example1 title2', 'body' => 'Example1 body2', 'email' => 'example1post2@gmail.com'],
  340. ]);
  341. $country->users()->create(['id' => 3, 'email' => 'example2@gmail.com', 'country_short' => 'uk'])
  342. ->posts()->createMany([
  343. ['title' => 'Example2 title1', 'body' => 'Example2 body1', 'email' => 'example2post1@gmail.com'],
  344. ['title' => 'Example2 title2', 'body' => 'Example2 body2', 'email' => 'example2post2@gmail.com'],
  345. ]);
  346. $country->users()->create(['id' => 4, 'email' => 'example3@gmail.com', 'country_short' => 'uk'])
  347. ->posts()->createMany([
  348. ['title' => 'Example3 title1', 'body' => 'Example3 body1', 'email' => 'example3post1@gmail.com'],
  349. ['title' => 'Example3 title2', 'body' => 'Example3 body2', 'email' => 'example3post2@gmail.com'],
  350. ]);
  351. }
  352. /**
  353. * Seed data for a default HasManyThrough setup.
  354. */
  355. protected function seedDefaultData()
  356. {
  357. HasManyThroughDefaultTestCountry::create(['id' => 1, 'name' => 'United States of America'])
  358. ->users()->create(['id' => 1, 'email' => 'taylorotwell@gmail.com'])
  359. ->posts()->createMany([
  360. ['title' => 'A title', 'body' => 'A body'],
  361. ['title' => 'Another title', 'body' => 'Another body'],
  362. ]);
  363. }
  364. /**
  365. * Drop the default tables.
  366. */
  367. protected function resetDefault()
  368. {
  369. $this->schema()->drop('users_default');
  370. $this->schema()->drop('posts_default');
  371. $this->schema()->drop('countries_default');
  372. }
  373. /**
  374. * Migrate tables for classes with a Laravel "default" HasManyThrough setup.
  375. */
  376. protected function migrateDefault()
  377. {
  378. $this->schema()->create('users_default', function ($table) {
  379. $table->increments('id');
  380. $table->string('email')->unique();
  381. $table->unsignedInteger('has_many_through_default_test_country_id');
  382. $table->timestamps();
  383. });
  384. $this->schema()->create('posts_default', function ($table) {
  385. $table->increments('id');
  386. $table->integer('has_many_through_default_test_user_id');
  387. $table->string('title');
  388. $table->text('body');
  389. $table->timestamps();
  390. });
  391. $this->schema()->create('countries_default', function ($table) {
  392. $table->increments('id');
  393. $table->string('name');
  394. $table->timestamps();
  395. });
  396. }
  397. /**
  398. * Get a database connection instance.
  399. *
  400. * @return \Illuminate\Database\Connection
  401. */
  402. protected function connection()
  403. {
  404. return Eloquent::getConnectionResolver()->connection();
  405. }
  406. /**
  407. * Get a schema builder instance.
  408. *
  409. * @return \Illuminate\Database\Schema\Builder
  410. */
  411. protected function schema()
  412. {
  413. return $this->connection()->getSchemaBuilder();
  414. }
  415. }
  416. /**
  417. * Eloquent Models...
  418. */
  419. class HasManyThroughTestUser extends Eloquent
  420. {
  421. protected $table = 'users';
  422. protected $guarded = [];
  423. public function posts()
  424. {
  425. return $this->hasMany(HasManyThroughTestPost::class, 'user_id');
  426. }
  427. }
  428. /**
  429. * Eloquent Models...
  430. */
  431. class HasManyThroughTestPost extends Eloquent
  432. {
  433. protected $table = 'posts';
  434. protected $guarded = [];
  435. public function owner()
  436. {
  437. return $this->belongsTo(HasManyThroughTestUser::class, 'user_id');
  438. }
  439. }
  440. class HasManyThroughTestCountry extends Eloquent
  441. {
  442. protected $table = 'countries';
  443. protected $guarded = [];
  444. public function posts()
  445. {
  446. return $this->hasManyThrough(HasManyThroughTestPost::class, HasManyThroughTestUser::class, 'country_id', 'user_id');
  447. }
  448. public function users()
  449. {
  450. return $this->hasMany(HasManyThroughTestUser::class, 'country_id');
  451. }
  452. }
  453. /**
  454. * Eloquent Models...
  455. */
  456. class HasManyThroughDefaultTestUser extends Eloquent
  457. {
  458. protected $table = 'users_default';
  459. protected $guarded = [];
  460. public function posts()
  461. {
  462. return $this->hasMany(HasManyThroughDefaultTestPost::class);
  463. }
  464. }
  465. /**
  466. * Eloquent Models...
  467. */
  468. class HasManyThroughDefaultTestPost extends Eloquent
  469. {
  470. protected $table = 'posts_default';
  471. protected $guarded = [];
  472. public function owner()
  473. {
  474. return $this->belongsTo(HasManyThroughDefaultTestUser::class);
  475. }
  476. }
  477. class HasManyThroughDefaultTestCountry extends Eloquent
  478. {
  479. protected $table = 'countries_default';
  480. protected $guarded = [];
  481. public function posts()
  482. {
  483. return $this->hasManyThrough(HasManyThroughDefaultTestPost::class, HasManyThroughDefaultTestUser::class);
  484. }
  485. public function users()
  486. {
  487. return $this->hasMany(HasManyThroughDefaultTestUser::class);
  488. }
  489. }
  490. class HasManyThroughIntermediateTestCountry extends Eloquent
  491. {
  492. protected $table = 'countries';
  493. protected $guarded = [];
  494. public function posts()
  495. {
  496. return $this->hasManyThrough(HasManyThroughTestPost::class, HasManyThroughTestUser::class, 'country_short', 'email', 'shortname', 'email');
  497. }
  498. public function users()
  499. {
  500. return $this->hasMany(HasManyThroughTestUser::class, 'country_id');
  501. }
  502. }
  503. class HasManyThroughSoftDeletesTestUser extends Eloquent
  504. {
  505. use SoftDeletes;
  506. protected $table = 'users';
  507. protected $guarded = [];
  508. public function posts()
  509. {
  510. return $this->hasMany(HasManyThroughSoftDeletesTestPost::class, 'user_id');
  511. }
  512. }
  513. /**
  514. * Eloquent Models...
  515. */
  516. class HasManyThroughSoftDeletesTestPost extends Eloquent
  517. {
  518. protected $table = 'posts';
  519. protected $guarded = [];
  520. public function owner()
  521. {
  522. return $this->belongsTo(HasManyThroughSoftDeletesTestUser::class, 'user_id');
  523. }
  524. }
  525. class HasManyThroughSoftDeletesTestCountry extends Eloquent
  526. {
  527. protected $table = 'countries';
  528. protected $guarded = [];
  529. public function posts()
  530. {
  531. return $this->hasManyThrough(HasManyThroughSoftDeletesTestPost::class, HasManyThroughTestUser::class, 'country_id', 'user_id');
  532. }
  533. public function users()
  534. {
  535. return $this->hasMany(HasManyThroughSoftDeletesTestUser::class, 'country_id');
  536. }
  537. }