DatabaseEloquentBuilderTest.php 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029
  1. <?php
  2. namespace Illuminate\Tests\Database;
  3. use BadMethodCallException;
  4. use Closure;
  5. use Illuminate\Database\ConnectionInterface;
  6. use Illuminate\Database\ConnectionResolverInterface;
  7. use Illuminate\Database\Eloquent\Builder;
  8. use Illuminate\Database\Eloquent\Collection;
  9. use Illuminate\Database\Eloquent\Model;
  10. use Illuminate\Database\Eloquent\ModelNotFoundException;
  11. use Illuminate\Database\Eloquent\RelationNotFoundException;
  12. use Illuminate\Database\Eloquent\Relations\Relation;
  13. use Illuminate\Database\Eloquent\SoftDeletes;
  14. use Illuminate\Database\Query\Builder as BaseBuilder;
  15. use Illuminate\Database\Query\Grammars\Grammar;
  16. use Illuminate\Database\Query\Processors\Processor;
  17. use Illuminate\Support\Carbon;
  18. use Illuminate\Support\Collection as BaseCollection;
  19. use Mockery as m;
  20. use PHPUnit\Framework\TestCase;
  21. use stdClass;
  22. class DatabaseEloquentBuilderTest extends TestCase
  23. {
  24. protected function tearDown(): void
  25. {
  26. m::close();
  27. }
  28. public function testFindMethod()
  29. {
  30. $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]);
  31. $model = $this->getMockModel();
  32. $builder->setModel($model);
  33. $model->shouldReceive('getKeyType')->once()->andReturn('int');
  34. $builder->getQuery()->shouldReceive('where')->once()->with('foo_table.foo', '=', 'bar');
  35. $builder->shouldReceive('first')->with(['column'])->andReturn('baz');
  36. $result = $builder->find('bar', ['column']);
  37. $this->assertSame('baz', $result);
  38. }
  39. public function testFindManyMethod()
  40. {
  41. // ids are not empty
  42. $builder = m::mock(Builder::class.'[get]', [$this->getMockQueryBuilder()]);
  43. $builder->setModel($this->getMockModel());
  44. $builder->getQuery()->shouldReceive('whereIn')->once()->with('foo_table.foo', ['one', 'two']);
  45. $builder->shouldReceive('get')->with(['column'])->andReturn(['baz']);
  46. $result = $builder->findMany(['one', 'two'], ['column']);
  47. $this->assertEquals(['baz'], $result);
  48. // ids are empty array
  49. $builder = m::mock(Builder::class.'[get]', [$this->getMockQueryBuilder()]);
  50. $model = $this->getMockModel();
  51. $model->shouldReceive('newCollection')->once()->withNoArgs()->andReturn('emptycollection');
  52. $builder->setModel($model);
  53. $builder->getQuery()->shouldNotReceive('whereIn');
  54. $builder->shouldNotReceive('get');
  55. $result = $builder->findMany([], ['column']);
  56. $this->assertSame('emptycollection', $result);
  57. // ids are empty collection
  58. $builder = m::mock(Builder::class.'[get]', [$this->getMockQueryBuilder()]);
  59. $model = $this->getMockModel();
  60. $model->shouldReceive('newCollection')->once()->withNoArgs()->andReturn('emptycollection');
  61. $builder->setModel($model);
  62. $builder->getQuery()->shouldNotReceive('whereIn');
  63. $builder->shouldNotReceive('get');
  64. $result = $builder->findMany(collect(), ['column']);
  65. $this->assertSame('emptycollection', $result);
  66. }
  67. public function testFindOrNewMethodModelFound()
  68. {
  69. $model = $this->getMockModel();
  70. $model->shouldReceive('getKeyType')->once()->andReturn('int');
  71. $model->shouldReceive('findOrNew')->once()->andReturn('baz');
  72. $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]);
  73. $builder->setModel($model);
  74. $builder->getQuery()->shouldReceive('where')->once()->with('foo_table.foo', '=', 'bar');
  75. $builder->shouldReceive('first')->with(['column'])->andReturn('baz');
  76. $expected = $model->findOrNew('bar', ['column']);
  77. $result = $builder->find('bar', ['column']);
  78. $this->assertEquals($expected, $result);
  79. }
  80. public function testFindOrNewMethodModelNotFound()
  81. {
  82. $model = $this->getMockModel();
  83. $model->shouldReceive('getKeyType')->once()->andReturn('int');
  84. $model->shouldReceive('findOrNew')->once()->andReturn(m::mock(Model::class));
  85. $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]);
  86. $builder->setModel($model);
  87. $builder->getQuery()->shouldReceive('where')->once()->with('foo_table.foo', '=', 'bar');
  88. $builder->shouldReceive('first')->with(['column'])->andReturn(null);
  89. $result = $model->findOrNew('bar', ['column']);
  90. $findResult = $builder->find('bar', ['column']);
  91. $this->assertNull($findResult);
  92. $this->assertInstanceOf(Model::class, $result);
  93. }
  94. public function testFindOrFailMethodThrowsModelNotFoundException()
  95. {
  96. $this->expectException(ModelNotFoundException::class);
  97. $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]);
  98. $model = $this->getMockModel();
  99. $model->shouldReceive('getKeyType')->once()->andReturn('int');
  100. $builder->setModel($model);
  101. $builder->getQuery()->shouldReceive('where')->once()->with('foo_table.foo', '=', 'bar');
  102. $builder->shouldReceive('first')->with(['column'])->andReturn(null);
  103. $builder->findOrFail('bar', ['column']);
  104. }
  105. public function testFindOrFailMethodWithManyThrowsModelNotFoundException()
  106. {
  107. $this->expectException(ModelNotFoundException::class);
  108. $builder = m::mock(Builder::class.'[get]', [$this->getMockQueryBuilder()]);
  109. $builder->setModel($this->getMockModel());
  110. $builder->getQuery()->shouldReceive('whereIn')->once()->with('foo_table.foo', [1, 2]);
  111. $builder->shouldReceive('get')->with(['column'])->andReturn(new Collection([1]));
  112. $builder->findOrFail([1, 2], ['column']);
  113. }
  114. public function testFindOrFailMethodWithManyUsingCollectionThrowsModelNotFoundException()
  115. {
  116. $this->expectException(ModelNotFoundException::class);
  117. $builder = m::mock(Builder::class.'[get]', [$this->getMockQueryBuilder()]);
  118. $builder->setModel($this->getMockModel());
  119. $builder->getQuery()->shouldReceive('whereIn')->once()->with('foo_table.foo', [1, 2]);
  120. $builder->shouldReceive('get')->with(['column'])->andReturn(new Collection([1]));
  121. $builder->findOrFail(new Collection([1, 2]), ['column']);
  122. }
  123. public function testFirstOrFailMethodThrowsModelNotFoundException()
  124. {
  125. $this->expectException(ModelNotFoundException::class);
  126. $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]);
  127. $builder->setModel($this->getMockModel());
  128. $builder->shouldReceive('first')->with(['column'])->andReturn(null);
  129. $builder->firstOrFail(['column']);
  130. }
  131. public function testFindWithMany()
  132. {
  133. $builder = m::mock(Builder::class.'[get]', [$this->getMockQueryBuilder()]);
  134. $builder->getQuery()->shouldReceive('whereIn')->once()->with('foo_table.foo', [1, 2]);
  135. $builder->setModel($this->getMockModel());
  136. $builder->shouldReceive('get')->with(['column'])->andReturn('baz');
  137. $result = $builder->find([1, 2], ['column']);
  138. $this->assertSame('baz', $result);
  139. }
  140. public function testFindWithManyUsingCollection()
  141. {
  142. $ids = collect([1, 2]);
  143. $builder = m::mock(Builder::class.'[get]', [$this->getMockQueryBuilder()]);
  144. $builder->getQuery()->shouldReceive('whereIn')->once()->with('foo_table.foo', [1, 2]);
  145. $builder->setModel($this->getMockModel());
  146. $builder->shouldReceive('get')->with(['column'])->andReturn('baz');
  147. $result = $builder->find($ids, ['column']);
  148. $this->assertSame('baz', $result);
  149. }
  150. public function testFirstMethod()
  151. {
  152. $builder = m::mock(Builder::class.'[get,take]', [$this->getMockQueryBuilder()]);
  153. $builder->shouldReceive('take')->with(1)->andReturnSelf();
  154. $builder->shouldReceive('get')->with(['*'])->andReturn(new Collection(['bar']));
  155. $result = $builder->first();
  156. $this->assertSame('bar', $result);
  157. }
  158. public function testQualifyColumn()
  159. {
  160. $builder = new Builder(m::mock(BaseBuilder::class));
  161. $builder->shouldReceive('from')->with('stub');
  162. $builder->setModel(new EloquentModelStub);
  163. $this->assertSame('stub.column', $builder->qualifyColumn('column'));
  164. }
  165. public function testQualifyColumns()
  166. {
  167. $builder = new Builder(m::mock(BaseBuilder::class));
  168. $builder->shouldReceive('from')->with('stub');
  169. $builder->setModel(new EloquentModelStub);
  170. $this->assertEquals(['stub.column', 'stub.name'], $builder->qualifyColumns(['column', 'name']));
  171. }
  172. public function testGetMethodLoadsModelsAndHydratesEagerRelations()
  173. {
  174. $builder = m::mock(Builder::class.'[getModels,eagerLoadRelations]', [$this->getMockQueryBuilder()]);
  175. $builder->shouldReceive('applyScopes')->andReturnSelf();
  176. $builder->shouldReceive('getModels')->with(['foo'])->andReturn(['bar']);
  177. $builder->shouldReceive('eagerLoadRelations')->with(['bar'])->andReturn(['bar', 'baz']);
  178. $builder->setModel($this->getMockModel());
  179. $builder->getModel()->shouldReceive('newCollection')->with(['bar', 'baz'])->andReturn(new Collection(['bar', 'baz']));
  180. $results = $builder->get(['foo']);
  181. $this->assertEquals(['bar', 'baz'], $results->all());
  182. }
  183. public function testGetMethodDoesntHydrateEagerRelationsWhenNoResultsAreReturned()
  184. {
  185. $builder = m::mock(Builder::class.'[getModels,eagerLoadRelations]', [$this->getMockQueryBuilder()]);
  186. $builder->shouldReceive('applyScopes')->andReturnSelf();
  187. $builder->shouldReceive('getModels')->with(['foo'])->andReturn([]);
  188. $builder->shouldReceive('eagerLoadRelations')->never();
  189. $builder->setModel($this->getMockModel());
  190. $builder->getModel()->shouldReceive('newCollection')->with([])->andReturn(new Collection([]));
  191. $results = $builder->get(['foo']);
  192. $this->assertEquals([], $results->all());
  193. }
  194. public function testValueMethodWithModelFound()
  195. {
  196. $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]);
  197. $mockModel = new stdClass;
  198. $mockModel->name = 'foo';
  199. $builder->shouldReceive('first')->with(['name'])->andReturn($mockModel);
  200. $this->assertSame('foo', $builder->value('name'));
  201. }
  202. public function testValueMethodWithModelNotFound()
  203. {
  204. $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]);
  205. $builder->shouldReceive('first')->with(['name'])->andReturn(null);
  206. $this->assertNull($builder->value('name'));
  207. }
  208. public function testValueOrFailMethodWithModelFound()
  209. {
  210. $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]);
  211. $mockModel = new stdClass;
  212. $mockModel->name = 'foo';
  213. $builder->shouldReceive('first')->with(['name'])->andReturn($mockModel);
  214. $this->assertSame('foo', $builder->valueOrFail('name'));
  215. }
  216. public function testValueOrFailMethodWithModelNotFoundThrowsModelNotFoundException()
  217. {
  218. $this->expectException(ModelNotFoundException::class);
  219. $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]);
  220. $model = $this->getMockModel();
  221. $model->shouldReceive('getKeyType')->once()->andReturn('int');
  222. $builder->setModel($model);
  223. $builder->getQuery()->shouldReceive('where')->once()->with('foo_table.foo', '=', 'bar');
  224. $builder->shouldReceive('first')->with(['column'])->andReturn(null);
  225. $builder->whereKey('bar')->valueOrFail('column');
  226. }
  227. public function testChunkWithLastChunkComplete()
  228. {
  229. $builder = m::mock(Builder::class.'[forPage,get]', [$this->getMockQueryBuilder()]);
  230. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  231. $chunk1 = new Collection(['foo1', 'foo2']);
  232. $chunk2 = new Collection(['foo3', 'foo4']);
  233. $chunk3 = new Collection([]);
  234. $builder->shouldReceive('forPage')->once()->with(1, 2)->andReturnSelf();
  235. $builder->shouldReceive('forPage')->once()->with(2, 2)->andReturnSelf();
  236. $builder->shouldReceive('forPage')->once()->with(3, 2)->andReturnSelf();
  237. $builder->shouldReceive('get')->times(3)->andReturn($chunk1, $chunk2, $chunk3);
  238. $callbackAssertor = m::mock(stdClass::class);
  239. $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk1);
  240. $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk2);
  241. $callbackAssertor->shouldReceive('doSomething')->never()->with($chunk3);
  242. $builder->chunk(2, function ($results) use ($callbackAssertor) {
  243. $callbackAssertor->doSomething($results);
  244. });
  245. }
  246. public function testChunkWithLastChunkPartial()
  247. {
  248. $builder = m::mock(Builder::class.'[forPage,get]', [$this->getMockQueryBuilder()]);
  249. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  250. $chunk1 = new Collection(['foo1', 'foo2']);
  251. $chunk2 = new Collection(['foo3']);
  252. $builder->shouldReceive('forPage')->once()->with(1, 2)->andReturnSelf();
  253. $builder->shouldReceive('forPage')->once()->with(2, 2)->andReturnSelf();
  254. $builder->shouldReceive('get')->times(2)->andReturn($chunk1, $chunk2);
  255. $callbackAssertor = m::mock(stdClass::class);
  256. $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk1);
  257. $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk2);
  258. $builder->chunk(2, function ($results) use ($callbackAssertor) {
  259. $callbackAssertor->doSomething($results);
  260. });
  261. }
  262. public function testChunkCanBeStoppedByReturningFalse()
  263. {
  264. $builder = m::mock(Builder::class.'[forPage,get]', [$this->getMockQueryBuilder()]);
  265. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  266. $chunk1 = new Collection(['foo1', 'foo2']);
  267. $chunk2 = new Collection(['foo3']);
  268. $builder->shouldReceive('forPage')->once()->with(1, 2)->andReturnSelf();
  269. $builder->shouldReceive('forPage')->never()->with(2, 2);
  270. $builder->shouldReceive('get')->times(1)->andReturn($chunk1);
  271. $callbackAssertor = m::mock(stdClass::class);
  272. $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk1);
  273. $callbackAssertor->shouldReceive('doSomething')->never()->with($chunk2);
  274. $builder->chunk(2, function ($results) use ($callbackAssertor) {
  275. $callbackAssertor->doSomething($results);
  276. return false;
  277. });
  278. }
  279. public function testChunkWithCountZero()
  280. {
  281. $builder = m::mock(Builder::class.'[forPage,get]', [$this->getMockQueryBuilder()]);
  282. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  283. $chunk = new Collection([]);
  284. $builder->shouldReceive('forPage')->once()->with(1, 0)->andReturnSelf();
  285. $builder->shouldReceive('get')->times(1)->andReturn($chunk);
  286. $callbackAssertor = m::mock(stdClass::class);
  287. $callbackAssertor->shouldReceive('doSomething')->never();
  288. $builder->chunk(0, function ($results) use ($callbackAssertor) {
  289. $callbackAssertor->doSomething($results);
  290. });
  291. }
  292. public function testChunkPaginatesUsingIdWithLastChunkComplete()
  293. {
  294. $builder = m::mock(Builder::class.'[forPageAfterId,get]', [$this->getMockQueryBuilder()]);
  295. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  296. $chunk1 = new Collection([(object) ['someIdField' => 1], (object) ['someIdField' => 2]]);
  297. $chunk2 = new Collection([(object) ['someIdField' => 10], (object) ['someIdField' => 11]]);
  298. $chunk3 = new Collection([]);
  299. $builder->shouldReceive('forPageAfterId')->once()->with(2, 0, 'someIdField')->andReturnSelf();
  300. $builder->shouldReceive('forPageAfterId')->once()->with(2, 2, 'someIdField')->andReturnSelf();
  301. $builder->shouldReceive('forPageAfterId')->once()->with(2, 11, 'someIdField')->andReturnSelf();
  302. $builder->shouldReceive('get')->times(3)->andReturn($chunk1, $chunk2, $chunk3);
  303. $callbackAssertor = m::mock(stdClass::class);
  304. $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk1);
  305. $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk2);
  306. $callbackAssertor->shouldReceive('doSomething')->never()->with($chunk3);
  307. $builder->chunkById(2, function ($results) use ($callbackAssertor) {
  308. $callbackAssertor->doSomething($results);
  309. }, 'someIdField');
  310. }
  311. public function testChunkPaginatesUsingIdWithLastChunkPartial()
  312. {
  313. $builder = m::mock(Builder::class.'[forPageAfterId,get]', [$this->getMockQueryBuilder()]);
  314. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  315. $chunk1 = new Collection([(object) ['someIdField' => 1], (object) ['someIdField' => 2]]);
  316. $chunk2 = new Collection([(object) ['someIdField' => 10]]);
  317. $builder->shouldReceive('forPageAfterId')->once()->with(2, 0, 'someIdField')->andReturnSelf();
  318. $builder->shouldReceive('forPageAfterId')->once()->with(2, 2, 'someIdField')->andReturnSelf();
  319. $builder->shouldReceive('get')->times(2)->andReturn($chunk1, $chunk2);
  320. $callbackAssertor = m::mock(stdClass::class);
  321. $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk1);
  322. $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk2);
  323. $builder->chunkById(2, function ($results) use ($callbackAssertor) {
  324. $callbackAssertor->doSomething($results);
  325. }, 'someIdField');
  326. }
  327. public function testChunkPaginatesUsingIdWithCountZero()
  328. {
  329. $builder = m::mock(Builder::class.'[forPageAfterId,get]', [$this->getMockQueryBuilder()]);
  330. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  331. $chunk = new Collection([]);
  332. $builder->shouldReceive('forPageAfterId')->once()->with(0, 0, 'someIdField')->andReturnSelf();
  333. $builder->shouldReceive('get')->times(1)->andReturn($chunk);
  334. $callbackAssertor = m::mock(stdClass::class);
  335. $callbackAssertor->shouldReceive('doSomething')->never();
  336. $builder->chunkById(0, function ($results) use ($callbackAssertor) {
  337. $callbackAssertor->doSomething($results);
  338. }, 'someIdField');
  339. }
  340. public function testLazyWithLastChunkComplete()
  341. {
  342. $builder = m::mock(Builder::class.'[forPage,get]', [$this->getMockQueryBuilder()]);
  343. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  344. $builder->shouldReceive('forPage')->once()->with(1, 2)->andReturnSelf();
  345. $builder->shouldReceive('forPage')->once()->with(2, 2)->andReturnSelf();
  346. $builder->shouldReceive('forPage')->once()->with(3, 2)->andReturnSelf();
  347. $builder->shouldReceive('get')->times(3)->andReturn(
  348. new Collection(['foo1', 'foo2']),
  349. new Collection(['foo3', 'foo4']),
  350. new Collection([])
  351. );
  352. $this->assertEquals(
  353. ['foo1', 'foo2', 'foo3', 'foo4'],
  354. $builder->lazy(2)->all()
  355. );
  356. }
  357. public function testLazyWithLastChunkPartial()
  358. {
  359. $builder = m::mock(Builder::class.'[forPage,get]', [$this->getMockQueryBuilder()]);
  360. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  361. $builder->shouldReceive('forPage')->once()->with(1, 2)->andReturnSelf();
  362. $builder->shouldReceive('forPage')->once()->with(2, 2)->andReturnSelf();
  363. $builder->shouldReceive('get')->times(2)->andReturn(
  364. new Collection(['foo1', 'foo2']),
  365. new Collection(['foo3'])
  366. );
  367. $this->assertEquals(
  368. ['foo1', 'foo2', 'foo3'],
  369. $builder->lazy(2)->all()
  370. );
  371. }
  372. public function testLazyIsLazy()
  373. {
  374. $builder = m::mock(Builder::class.'[forPage,get]', [$this->getMockQueryBuilder()]);
  375. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  376. $builder->shouldReceive('forPage')->once()->with(1, 2)->andReturnSelf();
  377. $builder->shouldReceive('get')->once()->andReturn(new Collection(['foo1', 'foo2']));
  378. $this->assertEquals(['foo1', 'foo2'], $builder->lazy(2)->take(2)->all());
  379. }
  380. public function testLazyByIdWithLastChunkComplete()
  381. {
  382. $builder = m::mock(Builder::class.'[forPageAfterId,get]', [$this->getMockQueryBuilder()]);
  383. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  384. $chunk1 = new Collection([(object) ['someIdField' => 1], (object) ['someIdField' => 2]]);
  385. $chunk2 = new Collection([(object) ['someIdField' => 10], (object) ['someIdField' => 11]]);
  386. $chunk3 = new Collection([]);
  387. $builder->shouldReceive('forPageAfterId')->once()->with(2, 0, 'someIdField')->andReturnSelf();
  388. $builder->shouldReceive('forPageAfterId')->once()->with(2, 2, 'someIdField')->andReturnSelf();
  389. $builder->shouldReceive('forPageAfterId')->once()->with(2, 11, 'someIdField')->andReturnSelf();
  390. $builder->shouldReceive('get')->times(3)->andReturn($chunk1, $chunk2, $chunk3);
  391. $this->assertEquals(
  392. [
  393. (object) ['someIdField' => 1],
  394. (object) ['someIdField' => 2],
  395. (object) ['someIdField' => 10],
  396. (object) ['someIdField' => 11],
  397. ],
  398. $builder->lazyById(2, 'someIdField')->all()
  399. );
  400. }
  401. public function testLazyByIdWithLastChunkPartial()
  402. {
  403. $builder = m::mock(Builder::class.'[forPageAfterId,get]', [$this->getMockQueryBuilder()]);
  404. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  405. $chunk1 = new Collection([(object) ['someIdField' => 1], (object) ['someIdField' => 2]]);
  406. $chunk2 = new Collection([(object) ['someIdField' => 10]]);
  407. $builder->shouldReceive('forPageAfterId')->once()->with(2, 0, 'someIdField')->andReturnSelf();
  408. $builder->shouldReceive('forPageAfterId')->once()->with(2, 2, 'someIdField')->andReturnSelf();
  409. $builder->shouldReceive('get')->times(2)->andReturn($chunk1, $chunk2);
  410. $this->assertEquals(
  411. [
  412. (object) ['someIdField' => 1],
  413. (object) ['someIdField' => 2],
  414. (object) ['someIdField' => 10],
  415. ],
  416. $builder->lazyById(2, 'someIdField')->all()
  417. );
  418. }
  419. public function testLazyByIdIsLazy()
  420. {
  421. $builder = m::mock(Builder::class.'[forPageAfterId,get]', [$this->getMockQueryBuilder()]);
  422. $builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
  423. $chunk1 = new Collection([(object) ['someIdField' => 1], (object) ['someIdField' => 2]]);
  424. $builder->shouldReceive('forPageAfterId')->once()->with(2, 0, 'someIdField')->andReturnSelf();
  425. $builder->shouldReceive('get')->once()->andReturn($chunk1);
  426. $this->assertEquals(
  427. [
  428. (object) ['someIdField' => 1],
  429. (object) ['someIdField' => 2],
  430. ],
  431. $builder->lazyById(2, 'someIdField')->take(2)->all()
  432. );
  433. }
  434. public function testPluckReturnsTheMutatedAttributesOfAModel()
  435. {
  436. $builder = $this->getBuilder();
  437. $builder->getQuery()->shouldReceive('pluck')->with('name', '')->andReturn(new BaseCollection(['bar', 'baz']));
  438. $builder->setModel($this->getMockModel());
  439. $builder->getModel()->shouldReceive('hasGetMutator')->with('name')->andReturn(true);
  440. $builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'bar'])->andReturn(new EloquentBuilderTestPluckStub(['name' => 'bar']));
  441. $builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'baz'])->andReturn(new EloquentBuilderTestPluckStub(['name' => 'baz']));
  442. $this->assertEquals(['foo_bar', 'foo_baz'], $builder->pluck('name')->all());
  443. }
  444. public function testPluckReturnsTheCastedAttributesOfAModel()
  445. {
  446. $builder = $this->getBuilder();
  447. $builder->getQuery()->shouldReceive('pluck')->with('name', '')->andReturn(new BaseCollection(['bar', 'baz']));
  448. $builder->setModel($this->getMockModel());
  449. $builder->getModel()->shouldReceive('hasGetMutator')->with('name')->andReturn(false);
  450. $builder->getModel()->shouldReceive('hasCast')->with('name')->andReturn(true);
  451. $builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'bar'])->andReturn(new EloquentBuilderTestPluckStub(['name' => 'bar']));
  452. $builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'baz'])->andReturn(new EloquentBuilderTestPluckStub(['name' => 'baz']));
  453. $this->assertEquals(['foo_bar', 'foo_baz'], $builder->pluck('name')->all());
  454. }
  455. public function testPluckReturnsTheDateAttributesOfAModel()
  456. {
  457. $builder = $this->getBuilder();
  458. $builder->getQuery()->shouldReceive('pluck')->with('created_at', '')->andReturn(new BaseCollection(['2010-01-01 00:00:00', '2011-01-01 00:00:00']));
  459. $builder->setModel($this->getMockModel());
  460. $builder->getModel()->shouldReceive('hasGetMutator')->with('created_at')->andReturn(false);
  461. $builder->getModel()->shouldReceive('hasCast')->with('created_at')->andReturn(false);
  462. $builder->getModel()->shouldReceive('getDates')->andReturn(['created_at']);
  463. $builder->getModel()->shouldReceive('newFromBuilder')->with(['created_at' => '2010-01-01 00:00:00'])->andReturn(new EloquentBuilderTestPluckDatesStub(['created_at' => '2010-01-01 00:00:00']));
  464. $builder->getModel()->shouldReceive('newFromBuilder')->with(['created_at' => '2011-01-01 00:00:00'])->andReturn(new EloquentBuilderTestPluckDatesStub(['created_at' => '2011-01-01 00:00:00']));
  465. $this->assertEquals(['date_2010-01-01 00:00:00', 'date_2011-01-01 00:00:00'], $builder->pluck('created_at')->all());
  466. }
  467. public function testPluckWithoutModelGetterJustReturnsTheAttributesFoundInDatabase()
  468. {
  469. $builder = $this->getBuilder();
  470. $builder->getQuery()->shouldReceive('pluck')->with('name', '')->andReturn(new BaseCollection(['bar', 'baz']));
  471. $builder->setModel($this->getMockModel());
  472. $builder->getModel()->shouldReceive('hasGetMutator')->with('name')->andReturn(false);
  473. $builder->getModel()->shouldReceive('hasCast')->with('name')->andReturn(false);
  474. $builder->getModel()->shouldReceive('getDates')->andReturn(['created_at']);
  475. $this->assertEquals(['bar', 'baz'], $builder->pluck('name')->all());
  476. }
  477. public function testLocalMacrosAreCalledOnBuilder()
  478. {
  479. unset($_SERVER['__test.builder']);
  480. $builder = new Builder(new BaseBuilder(
  481. m::mock(ConnectionInterface::class),
  482. m::mock(Grammar::class),
  483. m::mock(Processor::class)
  484. ));
  485. $builder->macro('fooBar', function ($builder) {
  486. $_SERVER['__test.builder'] = $builder;
  487. return $builder;
  488. });
  489. $result = $builder->fooBar();
  490. $this->assertTrue($builder->hasMacro('fooBar'));
  491. $this->assertEquals($builder, $result);
  492. $this->assertEquals($builder, $_SERVER['__test.builder']);
  493. unset($_SERVER['__test.builder']);
  494. }
  495. public function testGlobalMacrosAreCalledOnBuilder()
  496. {
  497. Builder::macro('foo', function ($bar) {
  498. return $bar;
  499. });
  500. Builder::macro('bam', function () {
  501. return $this->getQuery();
  502. });
  503. $builder = $this->getBuilder();
  504. $this->assertTrue(Builder::hasGlobalMacro('foo'));
  505. $this->assertSame('bar', $builder->foo('bar'));
  506. $this->assertEquals($builder->bam(), $builder->getQuery());
  507. }
  508. public function testMissingStaticMacrosThrowsProperException()
  509. {
  510. $this->expectException(BadMethodCallException::class);
  511. $this->expectExceptionMessage('Call to undefined method Illuminate\Database\Eloquent\Builder::missingMacro()');
  512. Builder::missingMacro();
  513. }
  514. public function testGetModelsProperlyHydratesModels()
  515. {
  516. $builder = m::mock(Builder::class.'[get]', [$this->getMockQueryBuilder()]);
  517. $records[] = ['name' => 'taylor', 'age' => 26];
  518. $records[] = ['name' => 'dayle', 'age' => 28];
  519. $builder->getQuery()->shouldReceive('get')->once()->with(['foo'])->andReturn(new BaseCollection($records));
  520. $model = m::mock(Model::class.'[getTable,hydrate]');
  521. $model->shouldReceive('getTable')->once()->andReturn('foo_table');
  522. $builder->setModel($model);
  523. $model->shouldReceive('hydrate')->once()->with($records)->andReturn(new Collection(['hydrated']));
  524. $models = $builder->getModels(['foo']);
  525. $this->assertEquals(['hydrated'], $models);
  526. }
  527. public function testEagerLoadRelationsLoadTopLevelRelationships()
  528. {
  529. $builder = m::mock(Builder::class.'[eagerLoadRelation]', [$this->getMockQueryBuilder()]);
  530. $nop1 = function () {
  531. //
  532. };
  533. $nop2 = function () {
  534. //
  535. };
  536. $builder->setEagerLoads(['foo' => $nop1, 'foo.bar' => $nop2]);
  537. $builder->shouldAllowMockingProtectedMethods()->shouldReceive('eagerLoadRelation')->with(['models'], 'foo', $nop1)->andReturn(['foo']);
  538. $results = $builder->eagerLoadRelations(['models']);
  539. $this->assertEquals(['foo'], $results);
  540. }
  541. public function testRelationshipEagerLoadProcess()
  542. {
  543. $builder = m::mock(Builder::class.'[getRelation]', [$this->getMockQueryBuilder()]);
  544. $builder->setEagerLoads(['orders' => function ($query) {
  545. $_SERVER['__eloquent.constrain'] = $query;
  546. }]);
  547. $relation = m::mock(stdClass::class);
  548. $relation->shouldReceive('addEagerConstraints')->once()->with(['models']);
  549. $relation->shouldReceive('initRelation')->once()->with(['models'], 'orders')->andReturn(['models']);
  550. $relation->shouldReceive('getEager')->once()->andReturn(['results']);
  551. $relation->shouldReceive('match')->once()->with(['models'], ['results'], 'orders')->andReturn(['models.matched']);
  552. $builder->shouldReceive('getRelation')->once()->with('orders')->andReturn($relation);
  553. $results = $builder->eagerLoadRelations(['models']);
  554. $this->assertEquals(['models.matched'], $results);
  555. $this->assertEquals($relation, $_SERVER['__eloquent.constrain']);
  556. unset($_SERVER['__eloquent.constrain']);
  557. }
  558. public function testGetRelationProperlySetsNestedRelationships()
  559. {
  560. $builder = $this->getBuilder();
  561. $builder->setModel($this->getMockModel());
  562. $builder->getModel()->shouldReceive('newInstance->orders')->once()->andReturn($relation = m::mock(stdClass::class));
  563. $relationQuery = m::mock(stdClass::class);
  564. $relation->shouldReceive('getQuery')->andReturn($relationQuery);
  565. $relationQuery->shouldReceive('with')->once()->with(['lines' => null, 'lines.details' => null]);
  566. $builder->setEagerLoads(['orders' => null, 'orders.lines' => null, 'orders.lines.details' => null]);
  567. $builder->getRelation('orders');
  568. }
  569. public function testGetRelationProperlySetsNestedRelationshipsWithSimilarNames()
  570. {
  571. $builder = $this->getBuilder();
  572. $builder->setModel($this->getMockModel());
  573. $builder->getModel()->shouldReceive('newInstance->orders')->once()->andReturn($relation = m::mock(stdClass::class));
  574. $builder->getModel()->shouldReceive('newInstance->ordersGroups')->once()->andReturn($groupsRelation = m::mock(stdClass::class));
  575. $relationQuery = m::mock(stdClass::class);
  576. $relation->shouldReceive('getQuery')->andReturn($relationQuery);
  577. $groupRelationQuery = m::mock(stdClass::class);
  578. $groupsRelation->shouldReceive('getQuery')->andReturn($groupRelationQuery);
  579. $groupRelationQuery->shouldReceive('with')->once()->with(['lines' => null, 'lines.details' => null]);
  580. $builder->setEagerLoads(['orders' => null, 'ordersGroups' => null, 'ordersGroups.lines' => null, 'ordersGroups.lines.details' => null]);
  581. $builder->getRelation('orders');
  582. $builder->getRelation('ordersGroups');
  583. }
  584. public function testGetRelationThrowsException()
  585. {
  586. $this->expectException(RelationNotFoundException::class);
  587. $builder = $this->getBuilder();
  588. $builder->setModel($this->getMockModel());
  589. $builder->getRelation('invalid');
  590. }
  591. public function testEagerLoadParsingSetsProperRelationships()
  592. {
  593. $builder = $this->getBuilder();
  594. $builder->with(['orders', 'orders.lines']);
  595. $eagers = $builder->getEagerLoads();
  596. $this->assertEquals(['orders', 'orders.lines'], array_keys($eagers));
  597. $this->assertInstanceOf(Closure::class, $eagers['orders']);
  598. $this->assertInstanceOf(Closure::class, $eagers['orders.lines']);
  599. $builder = $this->getBuilder();
  600. $builder->with('orders', 'orders.lines');
  601. $eagers = $builder->getEagerLoads();
  602. $this->assertEquals(['orders', 'orders.lines'], array_keys($eagers));
  603. $this->assertInstanceOf(Closure::class, $eagers['orders']);
  604. $this->assertInstanceOf(Closure::class, $eagers['orders.lines']);
  605. $builder = $this->getBuilder();
  606. $builder->with(['orders.lines']);
  607. $eagers = $builder->getEagerLoads();
  608. $this->assertEquals(['orders', 'orders.lines'], array_keys($eagers));
  609. $this->assertInstanceOf(Closure::class, $eagers['orders']);
  610. $this->assertInstanceOf(Closure::class, $eagers['orders.lines']);
  611. $builder = $this->getBuilder();
  612. $builder->with(['orders' => function () {
  613. return 'foo';
  614. }]);
  615. $eagers = $builder->getEagerLoads();
  616. $this->assertSame('foo', $eagers['orders']());
  617. $builder = $this->getBuilder();
  618. $builder->with(['orders.lines' => function () {
  619. return 'foo';
  620. }]);
  621. $eagers = $builder->getEagerLoads();
  622. $this->assertInstanceOf(Closure::class, $eagers['orders']);
  623. $this->assertNull($eagers['orders']());
  624. $this->assertSame('foo', $eagers['orders.lines']());
  625. $builder = $this->getBuilder();
  626. $builder->with('orders.lines', function () {
  627. return 'foo';
  628. });
  629. $eagers = $builder->getEagerLoads();
  630. $this->assertInstanceOf(Closure::class, $eagers['orders']);
  631. $this->assertNull($eagers['orders']());
  632. $this->assertSame('foo', $eagers['orders.lines']());
  633. }
  634. public function testQueryPassThru()
  635. {
  636. $builder = $this->getBuilder();
  637. $builder->getQuery()->shouldReceive('foobar')->once()->andReturn('foo');
  638. $this->assertInstanceOf(Builder::class, $builder->foobar());
  639. $builder = $this->getBuilder();
  640. $builder->getQuery()->shouldReceive('insert')->once()->with(['bar'])->andReturn('foo');
  641. $this->assertSame('foo', $builder->insert(['bar']));
  642. $builder = $this->getBuilder();
  643. $builder->getQuery()->shouldReceive('insertOrIgnore')->once()->with(['bar'])->andReturn('foo');
  644. $this->assertSame('foo', $builder->insertOrIgnore(['bar']));
  645. $builder = $this->getBuilder();
  646. $builder->getQuery()->shouldReceive('insertGetId')->once()->with(['bar'])->andReturn('foo');
  647. $this->assertSame('foo', $builder->insertGetId(['bar']));
  648. $builder = $this->getBuilder();
  649. $builder->getQuery()->shouldReceive('insertUsing')->once()->with(['bar'], 'baz')->andReturn('foo');
  650. $this->assertSame('foo', $builder->insertUsing(['bar'], 'baz'));
  651. $builder = $this->getBuilder();
  652. $builder->getQuery()->shouldReceive('raw')->once()->with('bar')->andReturn('foo');
  653. $this->assertSame('foo', $builder->raw('bar'));
  654. $builder = $this->getBuilder();
  655. $grammar = new Grammar;
  656. $builder->getQuery()->shouldReceive('getGrammar')->once()->andReturn($grammar);
  657. $this->assertSame($grammar, $builder->getGrammar());
  658. }
  659. public function testQueryScopes()
  660. {
  661. $builder = $this->getBuilder();
  662. $builder->getQuery()->shouldReceive('from');
  663. $builder->getQuery()->shouldReceive('where')->once()->with('foo', 'bar');
  664. $builder->setModel($model = new EloquentBuilderTestScopeStub);
  665. $result = $builder->approved();
  666. $this->assertEquals($builder, $result);
  667. }
  668. public function testNestedWhere()
  669. {
  670. $nestedQuery = m::mock(Builder::class);
  671. $nestedRawQuery = $this->getMockQueryBuilder();
  672. $nestedQuery->shouldReceive('getQuery')->once()->andReturn($nestedRawQuery);
  673. $model = $this->getMockModel()->makePartial();
  674. $model->shouldReceive('newQueryWithoutRelationships')->once()->andReturn($nestedQuery);
  675. $builder = $this->getBuilder();
  676. $builder->getQuery()->shouldReceive('from');
  677. $builder->setModel($model);
  678. $builder->getQuery()->shouldReceive('addNestedWhereQuery')->once()->with($nestedRawQuery, 'and');
  679. $nestedQuery->shouldReceive('foo')->once();
  680. $result = $builder->where(function ($query) {
  681. $query->foo();
  682. });
  683. $this->assertEquals($builder, $result);
  684. }
  685. public function testRealNestedWhereWithScopes()
  686. {
  687. $model = new EloquentBuilderTestNestedStub;
  688. $this->mockConnectionForModel($model, 'SQLite');
  689. $query = $model->newQuery()->where('foo', '=', 'bar')->where(function ($query) {
  690. $query->where('baz', '>', 9000);
  691. });
  692. $this->assertSame('select * from "table" where "foo" = ? and ("baz" > ?) and "table"."deleted_at" is null', $query->toSql());
  693. $this->assertEquals(['bar', 9000], $query->getBindings());
  694. }
  695. public function testRealNestedWhereWithScopesMacro()
  696. {
  697. $model = new EloquentBuilderTestNestedStub;
  698. $this->mockConnectionForModel($model, 'SQLite');
  699. $query = $model->newQuery()->where('foo', '=', 'bar')->where(function ($query) {
  700. $query->where('baz', '>', 9000)->onlyTrashed();
  701. })->withTrashed();
  702. $this->assertSame('select * from "table" where "foo" = ? and ("baz" > ? and "table"."deleted_at" is not null)', $query->toSql());
  703. $this->assertEquals(['bar', 9000], $query->getBindings());
  704. }
  705. public function testRealNestedWhereWithMultipleScopesAndOneDeadScope()
  706. {
  707. $model = new EloquentBuilderTestNestedStub;
  708. $this->mockConnectionForModel($model, 'SQLite');
  709. $query = $model->newQuery()->empty()->where('foo', '=', 'bar')->empty()->where(function ($query) {
  710. $query->empty()->where('baz', '>', 9000);
  711. });
  712. $this->assertSame('select * from "table" where "foo" = ? and ("baz" > ?) and "table"."deleted_at" is null', $query->toSql());
  713. $this->assertEquals(['bar', 9000], $query->getBindings());
  714. }
  715. public function testRealQueryHigherOrderOrWhereScopes()
  716. {
  717. $model = new EloquentBuilderTestHigherOrderWhereScopeStub;
  718. $this->mockConnectionForModel($model, 'SQLite');
  719. $query = $model->newQuery()->one()->orWhere->two();
  720. $this->assertSame('select * from "table" where "one" = ? or ("two" = ?)', $query->toSql());
  721. }
  722. public function testRealQueryChainedHigherOrderOrWhereScopes()
  723. {
  724. $model = new EloquentBuilderTestHigherOrderWhereScopeStub;
  725. $this->mockConnectionForModel($model, 'SQLite');
  726. $query = $model->newQuery()->one()->orWhere->two()->orWhere->three();
  727. $this->assertSame('select * from "table" where "one" = ? or ("two" = ?) or ("three" = ?)', $query->toSql());
  728. }
  729. public function testSimpleWhere()
  730. {
  731. $builder = $this->getBuilder();
  732. $builder->getQuery()->shouldReceive('where')->once()->with('foo', '=', 'bar');
  733. $result = $builder->where('foo', '=', 'bar');
  734. $this->assertEquals($result, $builder);
  735. }
  736. public function testPostgresOperatorsWhere()
  737. {
  738. $builder = $this->getBuilder();
  739. $builder->getQuery()->shouldReceive('where')->once()->with('foo', '@>', 'bar');
  740. $result = $builder->where('foo', '@>', 'bar');
  741. $this->assertEquals($result, $builder);
  742. }
  743. public function testWhereBelongsTo()
  744. {
  745. $related = new EloquentBuilderTestWhereBelongsToStub([
  746. 'id' => 1,
  747. 'parent_id' => 2,
  748. ]);
  749. $parent = new EloquentBuilderTestWhereBelongsToStub([
  750. 'id' => 2,
  751. 'parent_id' => 1,
  752. ]);
  753. $builder = $this->getBuilder();
  754. $builder->shouldReceive('from')->with('eloquent_builder_test_where_belongs_to_stubs');
  755. $builder->setModel($related);
  756. $builder->getQuery()->shouldReceive('where')->once()->with('eloquent_builder_test_where_belongs_to_stubs.parent_id', '=', 2, 'and');
  757. $result = $builder->whereBelongsTo($parent);
  758. $this->assertEquals($result, $builder);
  759. $builder = $this->getBuilder();
  760. $builder->shouldReceive('from')->with('eloquent_builder_test_where_belongs_to_stubs');
  761. $builder->setModel($related);
  762. $builder->getQuery()->shouldReceive('where')->once()->with('eloquent_builder_test_where_belongs_to_stubs.parent_id', '=', 2, 'and');
  763. $result = $builder->whereBelongsTo($parent, 'parent');
  764. $this->assertEquals($result, $builder);
  765. }
  766. public function testDeleteOverride()
  767. {
  768. $builder = $this->getBuilder();
  769. $builder->onDelete(function ($builder) {
  770. return ['foo' => $builder];
  771. });
  772. $this->assertEquals(['foo' => $builder], $builder->delete());
  773. }
  774. public function testWithCount()
  775. {
  776. $model = new EloquentBuilderTestModelParentStub;
  777. $builder = $model->withCount('foo');
  778. $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  779. }
  780. public function testWithCountAndSelect()
  781. {
  782. $model = new EloquentBuilderTestModelParentStub;
  783. $builder = $model->select('id')->withCount('foo');
  784. $this->assertSame('select "id", (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  785. }
  786. public function testWithCountAndMergedWheres()
  787. {
  788. $model = new EloquentBuilderTestModelParentStub;
  789. $builder = $model->select('id')->withCount(['activeFoo' => function ($q) {
  790. $q->where('bam', '>', 'qux');
  791. }]);
  792. $this->assertSame('select "id", (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "bam" > ? and "active" = ?) as "active_foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  793. $this->assertEquals(['qux', true], $builder->getBindings());
  794. }
  795. public function testWithCountAndGlobalScope()
  796. {
  797. $model = new EloquentBuilderTestModelParentStub;
  798. EloquentBuilderTestModelCloseRelatedStub::addGlobalScope('withCount', function ($query) {
  799. return $query->addSelect('id');
  800. });
  801. $builder = $model->select('id')->withCount(['foo']);
  802. // Remove the global scope so it doesn't interfere with any other tests
  803. EloquentBuilderTestModelCloseRelatedStub::addGlobalScope('withCount', function ($query) {
  804. //
  805. });
  806. $this->assertSame('select "id", (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  807. }
  808. public function testWithMin()
  809. {
  810. $model = new EloquentBuilderTestModelParentStub;
  811. $builder = $model->withMin('foo', 'price');
  812. $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, (select min("eloquent_builder_test_model_close_related_stubs"."price") from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_min_price" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  813. }
  814. public function testWithMinOnBelongsToMany()
  815. {
  816. $model = new EloquentBuilderTestModelParentStub;
  817. $builder = $model->withMin('roles', 'id');
  818. $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, (select min("eloquent_builder_test_model_far_related_stubs"."id") from "eloquent_builder_test_model_far_related_stubs" inner join "user_role" on "eloquent_builder_test_model_far_related_stubs"."id" = "user_role"."related_id" where "eloquent_builder_test_model_parent_stubs"."id" = "user_role"."self_id") as "roles_min_id" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  819. }
  820. public function testWithMinOnSelfRelated()
  821. {
  822. $model = new EloquentBuilderTestModelSelfRelatedStub;
  823. $sql = $model->withMin('childFoos', 'created_at')->toSql();
  824. // alias has a dynamic hash, so replace with a static string for comparison
  825. $alias = 'self_alias_hash';
  826. $aliasRegex = '/\b(laravel_reserved_\d)(\b|$)/i';
  827. $sql = preg_replace($aliasRegex, $alias, $sql);
  828. $this->assertSame('select "self_related_stubs".*, (select min("self_alias_hash"."created_at") from "self_related_stubs" as "self_alias_hash" where "self_related_stubs"."id" = "self_alias_hash"."parent_id") as "child_foos_min_created_at" from "self_related_stubs"', $sql);
  829. }
  830. public function testWithCountAndConstraintsAndHaving()
  831. {
  832. $model = new EloquentBuilderTestModelParentStub;
  833. $builder = $model->where('bar', 'baz');
  834. $builder->withCount(['foo' => function ($q) {
  835. $q->where('bam', '>', 'qux');
  836. }])->having('foo_count', '>=', 1);
  837. $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "bam" > ?) as "foo_count" from "eloquent_builder_test_model_parent_stubs" where "bar" = ? having "foo_count" >= ?', $builder->toSql());
  838. $this->assertEquals(['qux', 'baz', 1], $builder->getBindings());
  839. }
  840. public function testWithCountAndRename()
  841. {
  842. $model = new EloquentBuilderTestModelParentStub;
  843. $builder = $model->withCount('foo as foo_bar');
  844. $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  845. }
  846. public function testWithCountMultipleAndPartialRename()
  847. {
  848. $model = new EloquentBuilderTestModelParentStub;
  849. $builder = $model->withCount(['foo as foo_bar', 'foo']);
  850. $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar", (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  851. }
  852. public function testWithExists()
  853. {
  854. $model = new EloquentBuilderTestModelParentStub;
  855. $builder = $model->withExists('foo');
  856. $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_exists" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  857. }
  858. public function testWithExistsAndSelect()
  859. {
  860. $model = new EloquentBuilderTestModelParentStub;
  861. $builder = $model->select('id')->withExists('foo');
  862. $this->assertSame('select "id", exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_exists" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  863. }
  864. public function testWithExistsAndMergedWheres()
  865. {
  866. $model = new EloquentBuilderTestModelParentStub;
  867. $builder = $model->select('id')->withExists(['activeFoo' => function ($q) {
  868. $q->where('bam', '>', 'qux');
  869. }]);
  870. $this->assertSame('select "id", exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "bam" > ? and "active" = ?) as "active_foo_exists" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  871. $this->assertEquals(['qux', true], $builder->getBindings());
  872. }
  873. public function testWithExistsAndGlobalScope()
  874. {
  875. $model = new EloquentBuilderTestModelParentStub;
  876. EloquentBuilderTestModelCloseRelatedStub::addGlobalScope('withExists', function ($query) {
  877. return $query->addSelect('id');
  878. });
  879. $builder = $model->select('id')->withExists(['foo']);
  880. // Remove the global scope so it doesn't interfere with any other tests
  881. EloquentBuilderTestModelCloseRelatedStub::addGlobalScope('withExists', function ($query) {
  882. //
  883. });
  884. $this->assertSame('select "id", exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_exists" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  885. }
  886. public function testWithExistsOnBelongsToMany()
  887. {
  888. $model = new EloquentBuilderTestModelParentStub;
  889. $builder = $model->withExists('roles');
  890. $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, exists(select * from "eloquent_builder_test_model_far_related_stubs" inner join "user_role" on "eloquent_builder_test_model_far_related_stubs"."id" = "user_role"."related_id" where "eloquent_builder_test_model_parent_stubs"."id" = "user_role"."self_id") as "roles_exists" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  891. }
  892. public function testWithExistsOnSelfRelated()
  893. {
  894. $model = new EloquentBuilderTestModelSelfRelatedStub;
  895. $sql = $model->withExists('childFoos')->toSql();
  896. // alias has a dynamic hash, so replace with a static string for comparison
  897. $alias = 'self_alias_hash';
  898. $aliasRegex = '/\b(laravel_reserved_\d)(\b|$)/i';
  899. $sql = preg_replace($aliasRegex, $alias, $sql);
  900. $this->assertSame('select "self_related_stubs".*, exists(select * from "self_related_stubs" as "self_alias_hash" where "self_related_stubs"."id" = "self_alias_hash"."parent_id") as "child_foos_exists" from "self_related_stubs"', $sql);
  901. }
  902. public function testWithExistsAndRename()
  903. {
  904. $model = new EloquentBuilderTestModelParentStub;
  905. $builder = $model->withExists('foo as foo_bar');
  906. $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  907. }
  908. public function testWithExistsMultipleAndPartialRename()
  909. {
  910. $model = new EloquentBuilderTestModelParentStub;
  911. $builder = $model->withExists(['foo as foo_bar', 'foo']);
  912. $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar", exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_exists" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  913. }
  914. public function testHasWithConstraintsAndHavingInSubquery()
  915. {
  916. $model = new EloquentBuilderTestModelParentStub;
  917. $builder = $model->where('bar', 'baz');
  918. $builder->whereHas('foo', function ($q) {
  919. $q->having('bam', '>', 'qux');
  920. })->where('quux', 'quuux');
  921. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "bar" = ? and exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" having "bam" > ?) and "quux" = ?', $builder->toSql());
  922. $this->assertEquals(['baz', 'qux', 'quuux'], $builder->getBindings());
  923. }
  924. public function testHasWithConstraintsWithOrWhereAndHavingInSubquery()
  925. {
  926. $model = new EloquentBuilderTestModelParentStub;
  927. $builder = $model->where('name', 'larry');
  928. $builder->whereHas('address', function ($q) {
  929. $q->where('zipcode', '90210');
  930. $q->orWhere('zipcode', '90220');
  931. $q->having('street', '=', 'fooside dr');
  932. })->where('age', 29);
  933. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "name" = ? and exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and ("zipcode" = ? or "zipcode" = ?) having "street" = ?) and "age" = ?', $builder->toSql());
  934. $this->assertEquals(['larry', '90210', '90220', 'fooside dr', 29], $builder->getBindings());
  935. }
  936. public function testHasWithConstraintsAndJoinAndHavingInSubquery()
  937. {
  938. $model = new EloquentBuilderTestModelParentStub;
  939. $builder = $model->where('bar', 'baz');
  940. $builder->whereHas('foo', function ($q) {
  941. $q->join('quuuux', function ($j) {
  942. $j->where('quuuuux', '=', 'quuuuuux');
  943. });
  944. $q->having('bam', '>', 'qux');
  945. })->where('quux', 'quuux');
  946. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "bar" = ? and exists (select * from "eloquent_builder_test_model_close_related_stubs" inner join "quuuux" on "quuuuux" = ? where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" having "bam" > ?) and "quux" = ?', $builder->toSql());
  947. $this->assertEquals(['baz', 'quuuuuux', 'qux', 'quuux'], $builder->getBindings());
  948. }
  949. public function testHasWithConstraintsAndHavingInSubqueryWithCount()
  950. {
  951. $model = new EloquentBuilderTestModelParentStub;
  952. $builder = $model->where('bar', 'baz');
  953. $builder->whereHas('foo', function ($q) {
  954. $q->having('bam', '>', 'qux');
  955. }, '>=', 2)->where('quux', 'quuux');
  956. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "bar" = ? and (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" having "bam" > ?) >= 2 and "quux" = ?', $builder->toSql());
  957. $this->assertEquals(['baz', 'qux', 'quuux'], $builder->getBindings());
  958. }
  959. public function testWithCountAndConstraintsWithBindingInSelectSub()
  960. {
  961. $model = new EloquentBuilderTestModelParentStub;
  962. $builder = $model->newQuery();
  963. $builder->withCount(['foo' => function ($q) use ($model) {
  964. $q->selectSub($model->newQuery()->where('bam', '=', 3)->selectRaw('count(0)'), 'bam_3_count');
  965. }]);
  966. $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  967. $this->assertSame([], $builder->getBindings());
  968. }
  969. public function testWithExistsAndConstraintsWithBindingInSelectSub()
  970. {
  971. $model = new EloquentBuilderTestModelParentStub;
  972. $builder = $model->newQuery();
  973. $builder->withExists(['foo' => function ($q) use ($model) {
  974. $q->selectSub($model->newQuery()->where('bam', '=', 3)->selectRaw('count(0)'), 'bam_3_count');
  975. }]);
  976. $this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_exists" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
  977. $this->assertSame([], $builder->getBindings());
  978. }
  979. public function testHasNestedWithConstraints()
  980. {
  981. $model = new EloquentBuilderTestModelParentStub;
  982. $builder = $model->whereHas('foo', function ($q) {
  983. $q->whereHas('bar', function ($q) {
  984. $q->where('baz', 'bam');
  985. });
  986. })->toSql();
  987. $result = $model->whereHas('foo.bar', function ($q) {
  988. $q->where('baz', 'bam');
  989. })->toSql();
  990. $this->assertEquals($builder, $result);
  991. }
  992. public function testHasNested()
  993. {
  994. $model = new EloquentBuilderTestModelParentStub;
  995. $builder = $model->whereHas('foo', function ($q) {
  996. $q->has('bar');
  997. });
  998. $result = $model->has('foo.bar')->toSql();
  999. $this->assertEquals($builder->toSql(), $result);
  1000. }
  1001. public function testOrHasNested()
  1002. {
  1003. $model = new EloquentBuilderTestModelParentStub;
  1004. $builder = $model->whereHas('foo', function ($q) {
  1005. $q->has('bar');
  1006. })->orWhereHas('foo', function ($q) {
  1007. $q->has('baz');
  1008. });
  1009. $result = $model->has('foo.bar')->orHas('foo.baz')->toSql();
  1010. $this->assertEquals($builder->toSql(), $result);
  1011. }
  1012. public function testSelfHasNested()
  1013. {
  1014. $model = new EloquentBuilderTestModelSelfRelatedStub;
  1015. $nestedSql = $model->whereHas('parentFoo', function ($q) {
  1016. $q->has('childFoo');
  1017. })->toSql();
  1018. $dotSql = $model->has('parentFoo.childFoo')->toSql();
  1019. // alias has a dynamic hash, so replace with a static string for comparison
  1020. $alias = 'self_alias_hash';
  1021. $aliasRegex = '/\b(laravel_reserved_\d)(\b|$)/i';
  1022. $nestedSql = preg_replace($aliasRegex, $alias, $nestedSql);
  1023. $dotSql = preg_replace($aliasRegex, $alias, $dotSql);
  1024. $this->assertEquals($nestedSql, $dotSql);
  1025. }
  1026. public function testSelfHasNestedUsesAlias()
  1027. {
  1028. $model = new EloquentBuilderTestModelSelfRelatedStub;
  1029. $sql = $model->has('parentFoo.childFoo')->toSql();
  1030. // alias has a dynamic hash, so replace with a static string for comparison
  1031. $alias = 'self_alias_hash';
  1032. $aliasRegex = '/\b(laravel_reserved_\d)(\b|$)/i';
  1033. $sql = preg_replace($aliasRegex, $alias, $sql);
  1034. $this->assertStringContainsString('"self_alias_hash"."id" = "self_related_stubs"."parent_id"', $sql);
  1035. }
  1036. public function testDoesntHave()
  1037. {
  1038. $model = new EloquentBuilderTestModelParentStub;
  1039. $builder = $model->doesntHave('foo');
  1040. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where not exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id")', $builder->toSql());
  1041. }
  1042. public function testDoesntHaveNested()
  1043. {
  1044. $model = new EloquentBuilderTestModelParentStub;
  1045. $builder = $model->doesntHave('foo.bar');
  1046. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where not exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and exists (select * from "eloquent_builder_test_model_far_related_stubs" where "eloquent_builder_test_model_close_related_stubs"."id" = "eloquent_builder_test_model_far_related_stubs"."eloquent_builder_test_model_close_related_stub_id"))', $builder->toSql());
  1047. }
  1048. public function testOrDoesntHave()
  1049. {
  1050. $model = new EloquentBuilderTestModelParentStub;
  1051. $builder = $model->where('bar', 'baz')->orDoesntHave('foo');
  1052. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "bar" = ? or not exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id")', $builder->toSql());
  1053. $this->assertEquals(['baz'], $builder->getBindings());
  1054. }
  1055. public function testWhereDoesntHave()
  1056. {
  1057. $model = new EloquentBuilderTestModelParentStub;
  1058. $builder = $model->whereDoesntHave('foo', function ($query) {
  1059. $query->where('bar', 'baz');
  1060. });
  1061. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where not exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "bar" = ?)', $builder->toSql());
  1062. $this->assertEquals(['baz'], $builder->getBindings());
  1063. }
  1064. public function testOrWhereDoesntHave()
  1065. {
  1066. $model = new EloquentBuilderTestModelParentStub;
  1067. $builder = $model->where('bar', 'baz')->orWhereDoesntHave('foo', function ($query) {
  1068. $query->where('qux', 'quux');
  1069. });
  1070. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "bar" = ? or not exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "qux" = ?)', $builder->toSql());
  1071. $this->assertEquals(['baz', 'quux'], $builder->getBindings());
  1072. }
  1073. public function testWhereMorphedTo()
  1074. {
  1075. $model = new EloquentBuilderTestModelParentStub;
  1076. $this->mockConnectionForModel($model, '');
  1077. $relatedModel = new EloquentBuilderTestModelCloseRelatedStub;
  1078. $relatedModel->id = 1;
  1079. $builder = $model->whereMorphedTo('morph', $relatedModel);
  1080. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where ("morph_type" = ? and "morph_id" = ?)', $builder->toSql());
  1081. $this->assertEquals([$relatedModel->getMorphClass(), $relatedModel->getKey()], $builder->getBindings());
  1082. }
  1083. public function testOrWhereMorphedTo()
  1084. {
  1085. $model = new EloquentBuilderTestModelParentStub;
  1086. $this->mockConnectionForModel($model, '');
  1087. $relatedModel = new EloquentBuilderTestModelCloseRelatedStub;
  1088. $relatedModel->id = 1;
  1089. $builder = $model->where('bar', 'baz')->orWhereMorphedTo('morph', $relatedModel);
  1090. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "bar" = ? or ("morph_type" = ? and "morph_id" = ?)', $builder->toSql());
  1091. $this->assertEquals(['baz', $relatedModel->getMorphClass(), $relatedModel->getKey()], $builder->getBindings());
  1092. }
  1093. public function testWhereMorphedToClass()
  1094. {
  1095. $model = new EloquentBuilderTestModelParentStub;
  1096. $this->mockConnectionForModel($model, '');
  1097. $builder = $model->whereMorphedTo('morph', EloquentBuilderTestModelCloseRelatedStub::class);
  1098. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "morph_type" = ?', $builder->toSql());
  1099. $this->assertEquals([EloquentBuilderTestModelCloseRelatedStub::class], $builder->getBindings());
  1100. }
  1101. public function testWhereMorphedToAlias()
  1102. {
  1103. $model = new EloquentBuilderTestModelParentStub;
  1104. $this->mockConnectionForModel($model, '');
  1105. Relation::morphMap([
  1106. 'alias' => EloquentBuilderTestModelCloseRelatedStub::class,
  1107. ]);
  1108. $builder = $model->whereMorphedTo('morph', EloquentBuilderTestModelCloseRelatedStub::class);
  1109. $this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "morph_type" = ?', $builder->toSql());
  1110. $this->assertEquals(['alias'], $builder->getBindings());
  1111. Relation::morphMap([], false);
  1112. }
  1113. public function testWhereKeyMethodWithInt()
  1114. {
  1115. $model = $this->getMockModel();
  1116. $builder = $this->getBuilder()->setModel($model);
  1117. $keyName = $model->getQualifiedKeyName();
  1118. $int = 1;
  1119. $model->shouldReceive('getKeyType')->once()->andReturn('int');
  1120. $builder->getQuery()->shouldReceive('where')->once()->with($keyName, '=', $int);
  1121. $builder->whereKey($int);
  1122. }
  1123. public function testWhereKeyMethodWithStringZero()
  1124. {
  1125. $model = new EloquentBuilderTestStubStringPrimaryKey;
  1126. $builder = $this->getBuilder()->setModel($model);
  1127. $keyName = $model->getQualifiedKeyName();
  1128. $int = 0;
  1129. $builder->getQuery()->shouldReceive('where')->once()->with($keyName, '=', (string) $int);
  1130. $builder->whereKey($int);
  1131. }
  1132. public function testWhereKeyMethodWithStringNull()
  1133. {
  1134. $model = new EloquentBuilderTestStubStringPrimaryKey;
  1135. $builder = $this->getBuilder()->setModel($model);
  1136. $keyName = $model->getQualifiedKeyName();
  1137. $builder->getQuery()->shouldReceive('where')->once()->with($keyName, '=', m::on(function ($argument) {
  1138. return $argument === null;
  1139. }));
  1140. $builder->whereKey(null);
  1141. }
  1142. public function testWhereKeyMethodWithArray()
  1143. {
  1144. $model = $this->getMockModel();
  1145. $builder = $this->getBuilder()->setModel($model);
  1146. $keyName = $model->getQualifiedKeyName();
  1147. $array = [1, 2, 3];
  1148. $builder->getQuery()->shouldReceive('whereIn')->once()->with($keyName, $array);
  1149. $builder->whereKey($array);
  1150. }
  1151. public function testWhereKeyMethodWithCollection()
  1152. {
  1153. $model = $this->getMockModel();
  1154. $builder = $this->getBuilder()->setModel($model);
  1155. $keyName = $model->getQualifiedKeyName();
  1156. $collection = new Collection([1, 2, 3]);
  1157. $builder->getQuery()->shouldReceive('whereIn')->once()->with($keyName, $collection);
  1158. $builder->whereKey($collection);
  1159. }
  1160. public function testWhereKeyMethodWithModel()
  1161. {
  1162. $model = new EloquentBuilderTestStubStringPrimaryKey;
  1163. $builder = $this->getBuilder()->setModel($model);
  1164. $keyName = $model->getQualifiedKeyName();
  1165. $builder->getQuery()->shouldReceive('where')->once()->with($keyName, '=', m::on(function ($argument) {
  1166. return $argument === '1';
  1167. }));
  1168. $builder->whereKey(new class extends Model
  1169. {
  1170. protected $attributes = ['id' => 1];
  1171. });
  1172. }
  1173. public function testWhereKeyNotMethodWithStringZero()
  1174. {
  1175. $model = new EloquentBuilderTestStubStringPrimaryKey;
  1176. $builder = $this->getBuilder()->setModel($model);
  1177. $keyName = $model->getQualifiedKeyName();
  1178. $int = 0;
  1179. $builder->getQuery()->shouldReceive('where')->once()->with($keyName, '!=', (string) $int);
  1180. $builder->whereKeyNot($int);
  1181. }
  1182. public function testWhereKeyNotMethodWithStringNull()
  1183. {
  1184. $model = new EloquentBuilderTestStubStringPrimaryKey;
  1185. $builder = $this->getBuilder()->setModel($model);
  1186. $keyName = $model->getQualifiedKeyName();
  1187. $builder->getQuery()->shouldReceive('where')->once()->with($keyName, '!=', m::on(function ($argument) {
  1188. return $argument === null;
  1189. }));
  1190. $builder->whereKeyNot(null);
  1191. }
  1192. public function testWhereKeyNotMethodWithInt()
  1193. {
  1194. $model = $this->getMockModel();
  1195. $builder = $this->getBuilder()->setModel($model);
  1196. $keyName = $model->getQualifiedKeyName();
  1197. $int = 1;
  1198. $model->shouldReceive('getKeyType')->once()->andReturn('int');
  1199. $builder->getQuery()->shouldReceive('where')->once()->with($keyName, '!=', $int);
  1200. $builder->whereKeyNot($int);
  1201. }
  1202. public function testWhereKeyNotMethodWithArray()
  1203. {
  1204. $model = $this->getMockModel();
  1205. $builder = $this->getBuilder()->setModel($model);
  1206. $keyName = $model->getQualifiedKeyName();
  1207. $array = [1, 2, 3];
  1208. $builder->getQuery()->shouldReceive('whereNotIn')->once()->with($keyName, $array);
  1209. $builder->whereKeyNot($array);
  1210. }
  1211. public function testWhereKeyNotMethodWithCollection()
  1212. {
  1213. $model = $this->getMockModel();
  1214. $builder = $this->getBuilder()->setModel($model);
  1215. $keyName = $model->getQualifiedKeyName();
  1216. $collection = new Collection([1, 2, 3]);
  1217. $builder->getQuery()->shouldReceive('whereNotIn')->once()->with($keyName, $collection);
  1218. $builder->whereKeyNot($collection);
  1219. }
  1220. public function testWhereKeyNotMethodWithModel()
  1221. {
  1222. $model = new EloquentBuilderTestStubStringPrimaryKey;
  1223. $builder = $this->getBuilder()->setModel($model);
  1224. $keyName = $model->getQualifiedKeyName();
  1225. $builder->getQuery()->shouldReceive('where')->once()->with($keyName, '!=', m::on(function ($argument) {
  1226. return $argument === '1';
  1227. }));
  1228. $builder->whereKeyNot(new class extends Model
  1229. {
  1230. protected $attributes = ['id' => 1];
  1231. });
  1232. }
  1233. public function testWhereIn()
  1234. {
  1235. $model = new EloquentBuilderTestNestedStub;
  1236. $this->mockConnectionForModel($model, '');
  1237. $query = $model->newQuery()->withoutGlobalScopes()->whereIn('foo', $model->newQuery()->select('id'));
  1238. $expected = 'select * from "table" where "foo" in (select "id" from "table" where "table"."deleted_at" is null)';
  1239. $this->assertEquals($expected, $query->toSql());
  1240. }
  1241. public function testLatestWithoutColumnWithCreatedAt()
  1242. {
  1243. $model = $this->getMockModel();
  1244. $model->shouldReceive('getCreatedAtColumn')->andReturn('foo');
  1245. $builder = $this->getBuilder()->setModel($model);
  1246. $builder->getQuery()->shouldReceive('latest')->once()->with('foo');
  1247. $builder->latest();
  1248. }
  1249. public function testLatestWithoutColumnWithoutCreatedAt()
  1250. {
  1251. $model = $this->getMockModel();
  1252. $model->shouldReceive('getCreatedAtColumn')->andReturn(null);
  1253. $builder = $this->getBuilder()->setModel($model);
  1254. $builder->getQuery()->shouldReceive('latest')->once()->with('created_at');
  1255. $builder->latest();
  1256. }
  1257. public function testLatestWithColumn()
  1258. {
  1259. $model = $this->getMockModel();
  1260. $builder = $this->getBuilder()->setModel($model);
  1261. $builder->getQuery()->shouldReceive('latest')->once()->with('foo');
  1262. $builder->latest('foo');
  1263. }
  1264. public function testOldestWithoutColumnWithCreatedAt()
  1265. {
  1266. $model = $this->getMockModel();
  1267. $model->shouldReceive('getCreatedAtColumn')->andReturn('foo');
  1268. $builder = $this->getBuilder()->setModel($model);
  1269. $builder->getQuery()->shouldReceive('oldest')->once()->with('foo');
  1270. $builder->oldest();
  1271. }
  1272. public function testOldestWithoutColumnWithoutCreatedAt()
  1273. {
  1274. $model = $this->getMockModel();
  1275. $model->shouldReceive('getCreatedAtColumn')->andReturn(null);
  1276. $builder = $this->getBuilder()->setModel($model);
  1277. $builder->getQuery()->shouldReceive('oldest')->once()->with('created_at');
  1278. $builder->oldest();
  1279. }
  1280. public function testOldestWithColumn()
  1281. {
  1282. $model = $this->getMockModel();
  1283. $builder = $this->getBuilder()->setModel($model);
  1284. $builder->getQuery()->shouldReceive('oldest')->once()->with('foo');
  1285. $builder->oldest('foo');
  1286. }
  1287. public function testUpdate()
  1288. {
  1289. Carbon::setTestNow($now = '2017-10-10 10:10:10');
  1290. $query = new BaseBuilder(m::mock(ConnectionInterface::class), new Grammar, m::mock(Processor::class));
  1291. $builder = new Builder($query);
  1292. $model = new EloquentBuilderTestStub;
  1293. $this->mockConnectionForModel($model, '');
  1294. $builder->setModel($model);
  1295. $builder->getConnection()->shouldReceive('update')->once()
  1296. ->with('update "table" set "foo" = ?, "table"."updated_at" = ?', ['bar', $now])->andReturn(1);
  1297. $result = $builder->update(['foo' => 'bar']);
  1298. $this->assertEquals(1, $result);
  1299. Carbon::setTestNow(null);
  1300. }
  1301. public function testUpdateWithTimestampValue()
  1302. {
  1303. $query = new BaseBuilder(m::mock(ConnectionInterface::class), new Grammar, m::mock(Processor::class));
  1304. $builder = new Builder($query);
  1305. $model = new EloquentBuilderTestStub;
  1306. $this->mockConnectionForModel($model, '');
  1307. $builder->setModel($model);
  1308. $builder->getConnection()->shouldReceive('update')->once()
  1309. ->with('update "table" set "foo" = ?, "table"."updated_at" = ?', ['bar', null])->andReturn(1);
  1310. $result = $builder->update(['foo' => 'bar', 'updated_at' => null]);
  1311. $this->assertEquals(1, $result);
  1312. }
  1313. public function testUpdateWithQualifiedTimestampValue()
  1314. {
  1315. $query = new BaseBuilder(m::mock(ConnectionInterface::class), new Grammar, m::mock(Processor::class));
  1316. $builder = new Builder($query);
  1317. $model = new EloquentBuilderTestStub;
  1318. $this->mockConnectionForModel($model, '');
  1319. $builder->setModel($model);
  1320. $builder->getConnection()->shouldReceive('update')->once()
  1321. ->with('update "table" set "table"."foo" = ?, "table"."updated_at" = ?', ['bar', null])->andReturn(1);
  1322. $result = $builder->update(['table.foo' => 'bar', 'table.updated_at' => null]);
  1323. $this->assertEquals(1, $result);
  1324. }
  1325. public function testUpdateWithoutTimestamp()
  1326. {
  1327. $query = new BaseBuilder(m::mock(ConnectionInterface::class), new Grammar, m::mock(Processor::class));
  1328. $builder = new Builder($query);
  1329. $model = new EloquentBuilderTestStubWithoutTimestamp;
  1330. $this->mockConnectionForModel($model, '');
  1331. $builder->setModel($model);
  1332. $builder->getConnection()->shouldReceive('update')->once()
  1333. ->with('update "table" set "foo" = ?', ['bar'])->andReturn(1);
  1334. $result = $builder->update(['foo' => 'bar']);
  1335. $this->assertEquals(1, $result);
  1336. }
  1337. public function testUpdateWithAlias()
  1338. {
  1339. Carbon::setTestNow($now = '2017-10-10 10:10:10');
  1340. $query = new BaseBuilder(m::mock(ConnectionInterface::class), new Grammar, m::mock(Processor::class));
  1341. $builder = new Builder($query);
  1342. $model = new EloquentBuilderTestStub;
  1343. $this->mockConnectionForModel($model, '');
  1344. $builder->setModel($model);
  1345. $builder->getConnection()->shouldReceive('update')->once()
  1346. ->with('update "table" as "alias" set "foo" = ?, "alias"."updated_at" = ?', ['bar', $now])->andReturn(1);
  1347. $result = $builder->from('table as alias')->update(['foo' => 'bar']);
  1348. $this->assertEquals(1, $result);
  1349. Carbon::setTestNow(null);
  1350. }
  1351. public function testUpdateWithAliasWithQualifiedTimestampValue()
  1352. {
  1353. Carbon::setTestNow($now = '2017-10-10 10:10:10');
  1354. $query = new BaseBuilder(m::mock(ConnectionInterface::class), new Grammar, m::mock(Processor::class));
  1355. $builder = new Builder($query);
  1356. $model = new EloquentBuilderTestStub;
  1357. $this->mockConnectionForModel($model, '');
  1358. $builder->setModel($model);
  1359. $builder->getConnection()->shouldReceive('update')->once()
  1360. ->with('update "table" as "alias" set "foo" = ?, "alias"."updated_at" = ?', ['bar', null])->andReturn(1);
  1361. $result = $builder->from('table as alias')->update(['foo' => 'bar', 'alias.updated_at' => null]);
  1362. $this->assertEquals(1, $result);
  1363. Carbon::setTestNow(null);
  1364. }
  1365. public function testUpsert()
  1366. {
  1367. Carbon::setTestNow($now = '2017-10-10 10:10:10');
  1368. $query = m::mock(BaseBuilder::class);
  1369. $query->shouldReceive('from')->with('foo_table')->andReturn('foo_table');
  1370. $query->from = 'foo_table';
  1371. $builder = new Builder($query);
  1372. $model = new EloquentBuilderTestStubStringPrimaryKey;
  1373. $builder->setModel($model);
  1374. $query->shouldReceive('upsert')->once()
  1375. ->with([
  1376. ['email' => 'foo', 'name' => 'bar', 'updated_at' => $now, 'created_at' => $now],
  1377. ['name' => 'bar2', 'email' => 'foo2', 'updated_at' => $now, 'created_at' => $now],
  1378. ], ['email'], ['email', 'name', 'updated_at'])->andReturn(2);
  1379. $result = $builder->upsert([['email' => 'foo', 'name' => 'bar'], ['name' => 'bar2', 'email' => 'foo2']], ['email']);
  1380. $this->assertEquals(2, $result);
  1381. Carbon::setTestNow(null);
  1382. }
  1383. public function testWithCastsMethod()
  1384. {
  1385. $builder = new Builder($this->getMockQueryBuilder());
  1386. $model = $this->getMockModel();
  1387. $builder->setModel($model);
  1388. $model->shouldReceive('mergeCasts')->with(['foo' => 'bar'])->once();
  1389. $builder->withCasts(['foo' => 'bar']);
  1390. }
  1391. public function testClone()
  1392. {
  1393. $query = new BaseBuilder(m::mock(ConnectionInterface::class), new Grammar, m::mock(Processor::class));
  1394. $builder = new Builder($query);
  1395. $builder->select('*')->from('users');
  1396. $clone = $builder->clone()->where('email', 'foo');
  1397. $this->assertNotSame($builder, $clone);
  1398. $this->assertSame('select * from "users"', $builder->toSql());
  1399. $this->assertSame('select * from "users" where "email" = ?', $clone->toSql());
  1400. }
  1401. protected function mockConnectionForModel($model, $database)
  1402. {
  1403. $grammarClass = 'Illuminate\Database\Query\Grammars\\'.$database.'Grammar';
  1404. $processorClass = 'Illuminate\Database\Query\Processors\\'.$database.'Processor';
  1405. $grammar = new $grammarClass;
  1406. $processor = new $processorClass;
  1407. $connection = m::mock(ConnectionInterface::class, ['getQueryGrammar' => $grammar, 'getPostProcessor' => $processor]);
  1408. $connection->shouldReceive('query')->andReturnUsing(function () use ($connection, $grammar, $processor) {
  1409. return new BaseBuilder($connection, $grammar, $processor);
  1410. });
  1411. $connection->shouldReceive('getDatabaseName')->andReturn('database');
  1412. $resolver = m::mock(ConnectionResolverInterface::class, ['connection' => $connection]);
  1413. $class = get_class($model);
  1414. $class::setConnectionResolver($resolver);
  1415. }
  1416. protected function getBuilder()
  1417. {
  1418. return new Builder($this->getMockQueryBuilder());
  1419. }
  1420. protected function getMockModel()
  1421. {
  1422. $model = m::mock(Model::class);
  1423. $model->shouldReceive('getKeyName')->andReturn('foo');
  1424. $model->shouldReceive('getTable')->andReturn('foo_table');
  1425. $model->shouldReceive('getQualifiedKeyName')->andReturn('foo_table.foo');
  1426. return $model;
  1427. }
  1428. protected function getMockQueryBuilder()
  1429. {
  1430. $query = m::mock(BaseBuilder::class);
  1431. $query->shouldReceive('from')->with('foo_table');
  1432. return $query;
  1433. }
  1434. }
  1435. class EloquentBuilderTestStub extends Model
  1436. {
  1437. protected $table = 'table';
  1438. }
  1439. class EloquentBuilderTestScopeStub extends Model
  1440. {
  1441. public function scopeApproved($query)
  1442. {
  1443. $query->where('foo', 'bar');
  1444. }
  1445. }
  1446. class EloquentBuilderTestHigherOrderWhereScopeStub extends Model
  1447. {
  1448. protected $table = 'table';
  1449. public function scopeOne($query)
  1450. {
  1451. $query->where('one', 'foo');
  1452. }
  1453. public function scopeTwo($query)
  1454. {
  1455. $query->where('two', 'bar');
  1456. }
  1457. public function scopeThree($query)
  1458. {
  1459. $query->where('three', 'baz');
  1460. }
  1461. }
  1462. class EloquentBuilderTestNestedStub extends Model
  1463. {
  1464. protected $table = 'table';
  1465. use SoftDeletes;
  1466. public function scopeEmpty($query)
  1467. {
  1468. return $query;
  1469. }
  1470. }
  1471. class EloquentBuilderTestPluckStub
  1472. {
  1473. protected $attributes;
  1474. public function __construct($attributes)
  1475. {
  1476. $this->attributes = $attributes;
  1477. }
  1478. public function __get($key)
  1479. {
  1480. return 'foo_'.$this->attributes[$key];
  1481. }
  1482. }
  1483. class EloquentBuilderTestPluckDatesStub extends Model
  1484. {
  1485. protected $attributes;
  1486. public function __construct($attributes)
  1487. {
  1488. $this->attributes = $attributes;
  1489. }
  1490. protected function asDateTime($value)
  1491. {
  1492. return 'date_'.$value;
  1493. }
  1494. }
  1495. class EloquentBuilderTestModelParentStub extends Model
  1496. {
  1497. public function foo()
  1498. {
  1499. return $this->belongsTo(EloquentBuilderTestModelCloseRelatedStub::class);
  1500. }
  1501. public function address()
  1502. {
  1503. return $this->belongsTo(EloquentBuilderTestModelCloseRelatedStub::class, 'foo_id');
  1504. }
  1505. public function activeFoo()
  1506. {
  1507. return $this->belongsTo(EloquentBuilderTestModelCloseRelatedStub::class, 'foo_id')->where('active', true);
  1508. }
  1509. public function roles()
  1510. {
  1511. return $this->belongsToMany(
  1512. EloquentBuilderTestModelFarRelatedStub::class,
  1513. 'user_role',
  1514. 'self_id',
  1515. 'related_id'
  1516. );
  1517. }
  1518. public function morph()
  1519. {
  1520. return $this->morphTo();
  1521. }
  1522. }
  1523. class EloquentBuilderTestModelCloseRelatedStub extends Model
  1524. {
  1525. public function bar()
  1526. {
  1527. return $this->hasMany(EloquentBuilderTestModelFarRelatedStub::class);
  1528. }
  1529. public function baz()
  1530. {
  1531. return $this->hasMany(EloquentBuilderTestModelFarRelatedStub::class);
  1532. }
  1533. }
  1534. class EloquentBuilderTestModelFarRelatedStub extends Model
  1535. {
  1536. //
  1537. }
  1538. class EloquentBuilderTestModelSelfRelatedStub extends Model
  1539. {
  1540. protected $table = 'self_related_stubs';
  1541. public function parentFoo()
  1542. {
  1543. return $this->belongsTo(self::class, 'parent_id', 'id', 'parent');
  1544. }
  1545. public function childFoo()
  1546. {
  1547. return $this->hasOne(self::class, 'parent_id', 'id');
  1548. }
  1549. public function childFoos()
  1550. {
  1551. return $this->hasMany(self::class, 'parent_id', 'id', 'children');
  1552. }
  1553. public function parentBars()
  1554. {
  1555. return $this->belongsToMany(self::class, 'self_pivot', 'child_id', 'parent_id', 'parent_bars');
  1556. }
  1557. public function childBars()
  1558. {
  1559. return $this->belongsToMany(self::class, 'self_pivot', 'parent_id', 'child_id', 'child_bars');
  1560. }
  1561. public function bazes()
  1562. {
  1563. return $this->hasMany(EloquentBuilderTestModelFarRelatedStub::class, 'foreign_key', 'id', 'bar');
  1564. }
  1565. }
  1566. class EloquentBuilderTestStubWithoutTimestamp extends Model
  1567. {
  1568. const UPDATED_AT = null;
  1569. protected $table = 'table';
  1570. }
  1571. class EloquentBuilderTestStubStringPrimaryKey extends Model
  1572. {
  1573. public $incrementing = false;
  1574. protected $table = 'foo_table';
  1575. protected $keyType = 'string';
  1576. }
  1577. class EloquentBuilderTestWhereBelongsToStub extends Model
  1578. {
  1579. protected $fillable = [
  1580. 'id',
  1581. 'parent_id',
  1582. ];
  1583. public function eloquentBuilderTestWhereBelongsToStub()
  1584. {
  1585. return $this->belongsTo(self::class, 'parent_id', 'id', 'parent');
  1586. }
  1587. public function parent()
  1588. {
  1589. return $this->belongsTo(self::class, 'parent_id', 'id', 'parent');
  1590. }
  1591. }