QueryTest.php 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\ORM;
  16. use Cake\Database\Expression\IdentifierExpression;
  17. use Cake\Database\Expression\OrderByExpression;
  18. use Cake\Database\Expression\QueryExpression;
  19. use Cake\Database\TypeMap;
  20. use Cake\Datasource\ConnectionManager;
  21. use Cake\ORM\Query;
  22. use Cake\ORM\ResultSet;
  23. use Cake\ORM\Table;
  24. use Cake\ORM\TableRegistry;
  25. use Cake\TestSuite\TestCase;
  26. /**
  27. * Tests Query class
  28. */
  29. class QueryTest extends TestCase
  30. {
  31. /**
  32. * Fixture to be used
  33. *
  34. * @var array
  35. */
  36. public $fixtures = ['core.articles', 'core.authors', 'core.tags',
  37. 'core.comments', 'core.articles_tags', 'core.posts'];
  38. /**
  39. * setUp method
  40. *
  41. * @return void
  42. */
  43. public function setUp()
  44. {
  45. parent::setUp();
  46. $this->connection = ConnectionManager::get('test');
  47. $schema = [
  48. 'id' => ['type' => 'integer'],
  49. '_constraints' => [
  50. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  51. ]
  52. ];
  53. $schema1 = [
  54. 'id' => ['type' => 'integer'],
  55. 'name' => ['type' => 'string'],
  56. 'phone' => ['type' => 'string'],
  57. '_constraints' => [
  58. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  59. ]
  60. ];
  61. $schema2 = [
  62. 'id' => ['type' => 'integer'],
  63. 'total' => ['type' => 'string'],
  64. 'placed' => ['type' => 'datetime'],
  65. '_constraints' => [
  66. 'primary' => ['type' => 'primary', 'columns' => ['id']]
  67. ]
  68. ];
  69. $this->table = $table = TableRegistry::get('foo', ['schema' => $schema]);
  70. $clients = TableRegistry::get('clients', ['schema' => $schema1]);
  71. $orders = TableRegistry::get('orders', ['schema' => $schema2]);
  72. $companies = TableRegistry::get('companies', ['schema' => $schema, 'table' => 'organizations']);
  73. $orderTypes = TableRegistry::get('orderTypes', ['schema' => $schema]);
  74. $stuff = TableRegistry::get('stuff', ['schema' => $schema, 'table' => 'things']);
  75. $stuffTypes = TableRegistry::get('stuffTypes', ['schema' => $schema]);
  76. $categories = TableRegistry::get('categories', ['schema' => $schema]);
  77. $table->belongsTo('clients');
  78. $clients->hasOne('orders');
  79. $clients->belongsTo('companies');
  80. $orders->belongsTo('orderTypes');
  81. $orders->hasOne('stuff');
  82. $stuff->belongsTo('stuffTypes');
  83. $companies->belongsTo('categories');
  84. $this->fooTypeMap = new TypeMap(['foo.id' => 'integer', 'id' => 'integer']);
  85. }
  86. /**
  87. * tearDown method
  88. *
  89. * @return void
  90. */
  91. public function tearDown()
  92. {
  93. parent::tearDown();
  94. TableRegistry::clear();
  95. }
  96. /**
  97. * Data provider for the two types of strategies HasMany implements
  98. *
  99. * @return void
  100. */
  101. public function strategiesProviderHasMany()
  102. {
  103. return [['subquery'], ['select']];
  104. }
  105. /**
  106. * Data provider for the two types of strategies BelongsTo implements
  107. *
  108. * @return void
  109. */
  110. public function strategiesProviderBelongsTo()
  111. {
  112. return [['join'], ['select']];
  113. }
  114. /**
  115. * Data provider for the two types of strategies BelongsToMany implements
  116. *
  117. * @return void
  118. */
  119. public function strategiesProviderBelongsToMany()
  120. {
  121. return [['subquery'], ['select']];
  122. }
  123. /**
  124. * Tests that results are grouped correctly when using contain()
  125. * and results are not hydrated
  126. *
  127. * @dataProvider strategiesProviderBelongsTo
  128. * @return void
  129. */
  130. public function testContainResultFetchingOneLevel($strategy)
  131. {
  132. $table = TableRegistry::get('articles', ['table' => 'articles']);
  133. $table->belongsTo('authors', ['strategy' => $strategy]);
  134. $query = new Query($this->connection, $table);
  135. $results = $query->select()
  136. ->contain('authors')
  137. ->hydrate(false)
  138. ->order(['articles.id' => 'asc'])
  139. ->toArray();
  140. $expected = [
  141. [
  142. 'id' => 1,
  143. 'title' => 'First Article',
  144. 'body' => 'First Article Body',
  145. 'author_id' => 1,
  146. 'published' => 'Y',
  147. 'author' => [
  148. 'id' => 1,
  149. 'name' => 'mariano'
  150. ]
  151. ],
  152. [
  153. 'id' => 2,
  154. 'title' => 'Second Article',
  155. 'body' => 'Second Article Body',
  156. 'author_id' => 3,
  157. 'published' => 'Y',
  158. 'author' => [
  159. 'id' => 3,
  160. 'name' => 'larry'
  161. ]
  162. ],
  163. [
  164. 'id' => 3,
  165. 'title' => 'Third Article',
  166. 'body' => 'Third Article Body',
  167. 'author_id' => 1,
  168. 'published' => 'Y',
  169. 'author' => [
  170. 'id' => 1,
  171. 'name' => 'mariano'
  172. ]
  173. ],
  174. ];
  175. $this->assertEquals($expected, $results);
  176. }
  177. /**
  178. * Tests that HasMany associations are correctly eager loaded and results
  179. * correctly nested when no hydration is used
  180. * Also that the query object passes the correct parent model keys to the
  181. * association objects in order to perform eager loading with select strategy
  182. *
  183. * @dataProvider strategiesProviderHasMany
  184. * @return void
  185. */
  186. public function testHasManyEagerLoadingNoHydration($strategy)
  187. {
  188. $table = TableRegistry::get('authors');
  189. TableRegistry::get('articles');
  190. $table->hasMany('articles', [
  191. 'propertyName' => 'articles',
  192. 'strategy' => $strategy,
  193. 'sort' => ['articles.id' => 'asc']
  194. ]);
  195. $query = new Query($this->connection, $table);
  196. $results = $query->select()
  197. ->contain('articles')
  198. ->hydrate(false)
  199. ->toArray();
  200. $expected = [
  201. [
  202. 'id' => 1,
  203. 'name' => 'mariano',
  204. 'articles' => [
  205. [
  206. 'id' => 1,
  207. 'title' => 'First Article',
  208. 'body' => 'First Article Body',
  209. 'author_id' => 1,
  210. 'published' => 'Y',
  211. ],
  212. [
  213. 'id' => 3,
  214. 'title' => 'Third Article',
  215. 'body' => 'Third Article Body',
  216. 'author_id' => 1,
  217. 'published' => 'Y',
  218. ],
  219. ]
  220. ],
  221. [
  222. 'id' => 2,
  223. 'name' => 'nate',
  224. 'articles' => [],
  225. ],
  226. [
  227. 'id' => 3,
  228. 'name' => 'larry',
  229. 'articles' => [
  230. [
  231. 'id' => 2,
  232. 'title' => 'Second Article',
  233. 'body' => 'Second Article Body',
  234. 'author_id' => 3,
  235. 'published' => 'Y'
  236. ]
  237. ]
  238. ],
  239. [
  240. 'id' => 4,
  241. 'name' => 'garrett',
  242. 'articles' => [],
  243. ]
  244. ];
  245. $this->assertEquals($expected, $results);
  246. $results = $query->repository($table)
  247. ->select()
  248. ->contain(['articles' => ['conditions' => ['articles.id' => 2]]])
  249. ->hydrate(false)
  250. ->toArray();
  251. $expected[0]['articles'] = [];
  252. $this->assertEquals($expected, $results);
  253. $this->assertEquals($table->association('articles')->strategy(), $strategy);
  254. }
  255. /**
  256. * Tests that it is possible to count results containing hasMany associations
  257. * both hydrating and not hydrating the results.
  258. *
  259. * @dataProvider strategiesProviderHasMany
  260. * @return void
  261. */
  262. public function testHasManyEagerLoadingCount($strategy)
  263. {
  264. $table = TableRegistry::get('authors');
  265. TableRegistry::get('articles');
  266. $table->hasMany('articles', [
  267. 'property' => 'articles',
  268. 'strategy' => $strategy,
  269. 'sort' => ['articles.id' => 'asc']
  270. ]);
  271. $query = new Query($this->connection, $table);
  272. $query = $query->select()
  273. ->contain('articles');
  274. $expected = 4;
  275. $results = $query->hydrate(false)
  276. ->count();
  277. $this->assertEquals($expected, $results);
  278. $results = $query->hydrate(true)
  279. ->count();
  280. $this->assertEquals($expected, $results);
  281. }
  282. /**
  283. * Tests that it is possible to set fields & order in a hasMany result set
  284. *
  285. * @dataProvider strategiesProviderHasMany
  286. * @return void
  287. */
  288. public function testHasManyEagerLoadingFieldsAndOrderNoHydration($strategy)
  289. {
  290. $table = TableRegistry::get('authors');
  291. TableRegistry::get('articles');
  292. $table->hasMany('articles', ['propertyName' => 'articles'] + compact('strategy'));
  293. $query = new Query($this->connection, $table);
  294. $results = $query->select()
  295. ->contain([
  296. 'articles' => [
  297. 'fields' => ['title', 'author_id'],
  298. 'sort' => ['articles.id' => 'DESC']
  299. ]
  300. ])
  301. ->hydrate(false)
  302. ->toArray();
  303. $expected = [
  304. [
  305. 'id' => 1,
  306. 'name' => 'mariano',
  307. 'articles' => [
  308. ['title' => 'Third Article', 'author_id' => 1],
  309. ['title' => 'First Article', 'author_id' => 1],
  310. ]
  311. ],
  312. [
  313. 'id' => 2,
  314. 'name' => 'nate',
  315. 'articles' => [],
  316. ],
  317. [
  318. 'id' => 3,
  319. 'name' => 'larry',
  320. 'articles' => [
  321. ['title' => 'Second Article', 'author_id' => 3],
  322. ]
  323. ],
  324. [
  325. 'id' => 4,
  326. 'name' => 'garrett',
  327. 'articles' => [],
  328. ],
  329. ];
  330. $this->assertEquals($expected, $results);
  331. }
  332. /**
  333. * Tests that deep associations can be eagerly loaded
  334. *
  335. * @dataProvider strategiesProviderHasMany
  336. * @return void
  337. */
  338. public function testHasManyEagerLoadingDeep($strategy)
  339. {
  340. $table = TableRegistry::get('authors');
  341. $article = TableRegistry::get('articles');
  342. $table->hasMany('articles', [
  343. 'propertyName' => 'articles',
  344. 'strategy' => $strategy,
  345. 'sort' => ['articles.id' => 'asc']
  346. ]);
  347. $article->belongsTo('authors');
  348. $query = new Query($this->connection, $table);
  349. $results = $query->select()
  350. ->contain(['articles' => ['authors']])
  351. ->hydrate(false)
  352. ->toArray();
  353. $expected = [
  354. [
  355. 'id' => 1,
  356. 'name' => 'mariano',
  357. 'articles' => [
  358. [
  359. 'id' => 1,
  360. 'title' => 'First Article',
  361. 'author_id' => 1,
  362. 'body' => 'First Article Body',
  363. 'published' => 'Y',
  364. 'author' => ['id' => 1, 'name' => 'mariano']
  365. ],
  366. [
  367. 'id' => 3,
  368. 'title' => 'Third Article',
  369. 'author_id' => 1,
  370. 'body' => 'Third Article Body',
  371. 'published' => 'Y',
  372. 'author' => ['id' => 1, 'name' => 'mariano']
  373. ],
  374. ]
  375. ],
  376. [
  377. 'id' => 2,
  378. 'name' => 'nate',
  379. 'articles' => [],
  380. ],
  381. [
  382. 'id' => 3,
  383. 'name' => 'larry',
  384. 'articles' => [
  385. [
  386. 'id' => 2,
  387. 'title' => 'Second Article',
  388. 'author_id' => 3,
  389. 'body' => 'Second Article Body',
  390. 'published' => 'Y',
  391. 'author' => ['id' => 3, 'name' => 'larry']
  392. ],
  393. ]
  394. ],
  395. [
  396. 'id' => 4,
  397. 'name' => 'garrett',
  398. 'articles' => [],
  399. ]
  400. ];
  401. $this->assertEquals($expected, $results);
  402. }
  403. /**
  404. * Tests that hasMany associations can be loaded even when related to a secondary
  405. * model in the query
  406. *
  407. * @dataProvider strategiesProviderHasMany
  408. * @return void
  409. */
  410. public function testHasManyEagerLoadingFromSecondaryTable($strategy)
  411. {
  412. $author = TableRegistry::get('authors');
  413. $article = TableRegistry::get('articles');
  414. $post = TableRegistry::get('posts');
  415. $author->hasMany('posts', [
  416. 'sort' => ['posts.id' => 'ASC'],
  417. 'strategy' => $strategy
  418. ]);
  419. $article->belongsTo('authors');
  420. $query = new Query($this->connection, $article);
  421. $results = $query->select()
  422. ->contain(['authors' => ['posts']])
  423. ->order(['articles.id' => 'ASC'])
  424. ->hydrate(false)
  425. ->toArray();
  426. $expected = [
  427. [
  428. 'id' => 1,
  429. 'title' => 'First Article',
  430. 'body' => 'First Article Body',
  431. 'author_id' => 1,
  432. 'published' => 'Y',
  433. 'author' => [
  434. 'id' => 1,
  435. 'name' => 'mariano',
  436. 'posts' => [
  437. [
  438. 'id' => '1',
  439. 'title' => 'First Post',
  440. 'body' => 'First Post Body',
  441. 'author_id' => 1,
  442. 'published' => 'Y',
  443. ],
  444. [
  445. 'id' => '3',
  446. 'title' => 'Third Post',
  447. 'body' => 'Third Post Body',
  448. 'author_id' => 1,
  449. 'published' => 'Y',
  450. ],
  451. ]
  452. ]
  453. ],
  454. [
  455. 'id' => 2,
  456. 'title' => 'Second Article',
  457. 'body' => 'Second Article Body',
  458. 'author_id' => 3,
  459. 'published' => 'Y',
  460. 'author' => [
  461. 'id' => 3,
  462. 'name' => 'larry',
  463. 'posts' => [
  464. [
  465. 'id' => 2,
  466. 'title' => 'Second Post',
  467. 'body' => 'Second Post Body',
  468. 'author_id' => 3,
  469. 'published' => 'Y',
  470. ]
  471. ]
  472. ]
  473. ],
  474. [
  475. 'id' => 3,
  476. 'title' => 'Third Article',
  477. 'body' => 'Third Article Body',
  478. 'author_id' => 1,
  479. 'published' => 'Y',
  480. 'author' => [
  481. 'id' => 1,
  482. 'name' => 'mariano',
  483. 'posts' => [
  484. [
  485. 'id' => '1',
  486. 'title' => 'First Post',
  487. 'body' => 'First Post Body',
  488. 'author_id' => 1,
  489. 'published' => 'Y',
  490. ],
  491. [
  492. 'id' => '3',
  493. 'title' => 'Third Post',
  494. 'body' => 'Third Post Body',
  495. 'author_id' => 1,
  496. 'published' => 'Y',
  497. ],
  498. ]
  499. ]
  500. ],
  501. ];
  502. $this->assertEquals($expected, $results);
  503. }
  504. /**
  505. * Tests that BelongsToMany associations are correctly eager loaded.
  506. * Also that the query object passes the correct parent model keys to the
  507. * association objects in order to perform eager loading with select strategy
  508. *
  509. * @dataProvider strategiesProviderBelongsToMany
  510. * @return void
  511. */
  512. public function testBelongsToManyEagerLoadingNoHydration($strategy)
  513. {
  514. $table = TableRegistry::get('Articles');
  515. TableRegistry::get('Tags');
  516. TableRegistry::get('ArticlesTags', [
  517. 'table' => 'articles_tags'
  518. ]);
  519. $table->belongsToMany('Tags', ['strategy' => $strategy]);
  520. $query = new Query($this->connection, $table);
  521. $results = $query->select()->contain('Tags')->hydrate(false)->toArray();
  522. $expected = [
  523. [
  524. 'id' => 1,
  525. 'author_id' => 1,
  526. 'title' => 'First Article',
  527. 'body' => 'First Article Body',
  528. 'published' => 'Y',
  529. 'tags' => [
  530. [
  531. 'id' => 1,
  532. 'name' => 'tag1',
  533. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  534. ],
  535. [
  536. 'id' => 2,
  537. 'name' => 'tag2',
  538. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  539. ]
  540. ]
  541. ],
  542. [
  543. 'id' => 2,
  544. 'title' => 'Second Article',
  545. 'body' => 'Second Article Body',
  546. 'author_id' => 3,
  547. 'published' => 'Y',
  548. 'tags' => [
  549. [
  550. 'id' => 1,
  551. 'name' => 'tag1',
  552. '_joinData' => ['article_id' => 2, 'tag_id' => 1]
  553. ],
  554. [
  555. 'id' => 3,
  556. 'name' => 'tag3',
  557. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  558. ]
  559. ]
  560. ],
  561. [
  562. 'id' => 3,
  563. 'title' => 'Third Article',
  564. 'body' => 'Third Article Body',
  565. 'author_id' => 1,
  566. 'published' => 'Y',
  567. 'tags' => [],
  568. ],
  569. ];
  570. $this->assertEquals($expected, $results);
  571. $results = $query->select()
  572. ->contain(['Tags' => ['conditions' => ['Tags.id' => 3]]])
  573. ->hydrate(false)
  574. ->toArray();
  575. $expected = [
  576. [
  577. 'id' => 1,
  578. 'author_id' => 1,
  579. 'title' => 'First Article',
  580. 'body' => 'First Article Body',
  581. 'published' => 'Y',
  582. 'tags' => [],
  583. ],
  584. [
  585. 'id' => 2,
  586. 'title' => 'Second Article',
  587. 'body' => 'Second Article Body',
  588. 'author_id' => 3,
  589. 'published' => 'Y',
  590. 'tags' => [
  591. [
  592. 'id' => 3,
  593. 'name' => 'tag3',
  594. '_joinData' => ['article_id' => 2, 'tag_id' => 3]
  595. ]
  596. ]
  597. ],
  598. [
  599. 'id' => 3,
  600. 'title' => 'Third Article',
  601. 'body' => 'Third Article Body',
  602. 'author_id' => 1,
  603. 'published' => 'Y',
  604. 'tags' => [],
  605. ],
  606. ];
  607. $this->assertEquals($expected, $results);
  608. $this->assertEquals($table->association('Tags')->strategy(), $strategy);
  609. }
  610. /**
  611. * Tests that tables results can be filtered by the result of a HasMany
  612. *
  613. * @return void
  614. */
  615. public function testFilteringByHasManyNoHydration()
  616. {
  617. $query = new Query($this->connection, $this->table);
  618. $table = TableRegistry::get('authors');
  619. TableRegistry::get('articles');
  620. $table->hasMany('articles');
  621. $results = $query->repository($table)
  622. ->select()
  623. ->hydrate(false)
  624. ->matching('articles', function ($q) {
  625. return $q->where(['articles.id' => 2]);
  626. })
  627. ->toArray();
  628. $expected = [
  629. [
  630. 'id' => 3,
  631. 'name' => 'larry',
  632. '_matchingData' => [
  633. 'articles' => [
  634. 'id' => 2,
  635. 'title' => 'Second Article',
  636. 'body' => 'Second Article Body',
  637. 'author_id' => 3,
  638. 'published' => 'Y',
  639. ]
  640. ]
  641. ]
  642. ];
  643. $this->assertEquals($expected, $results);
  644. }
  645. /**
  646. * Tests that BelongsToMany associations are correctly eager loaded.
  647. * Also that the query object passes the correct parent model keys to the
  648. * association objects in order to perform eager loading with select strategy
  649. *
  650. * @return void
  651. */
  652. public function testFilteringByBelongsToManyNoHydration()
  653. {
  654. $query = new Query($this->connection, $this->table);
  655. $table = TableRegistry::get('Articles');
  656. TableRegistry::get('Tags');
  657. TableRegistry::get('ArticlesTags', [
  658. 'table' => 'articles_tags'
  659. ]);
  660. $table->belongsToMany('Tags');
  661. $results = $query->repository($table)->select()
  662. ->matching('Tags', function ($q) {
  663. return $q->where(['Tags.id' => 3]);
  664. })
  665. ->hydrate(false)
  666. ->toArray();
  667. $expected = [
  668. [
  669. 'id' => 2,
  670. 'author_id' => 3,
  671. 'title' => 'Second Article',
  672. 'body' => 'Second Article Body',
  673. 'published' => 'Y',
  674. '_matchingData' => [
  675. 'Tags' => [
  676. 'id' => 3,
  677. 'name' => 'tag3',
  678. ],
  679. 'ArticlesTags' => ['article_id' => 2, 'tag_id' => 3]
  680. ]
  681. ]
  682. ];
  683. $this->assertEquals($expected, $results);
  684. $query = new Query($this->connection, $table);
  685. $results = $query->select()
  686. ->matching('Tags', function ($q) {
  687. return $q->where(['Tags.name' => 'tag2']);
  688. })
  689. ->hydrate(false)
  690. ->toArray();
  691. $expected = [
  692. [
  693. 'id' => 1,
  694. 'title' => 'First Article',
  695. 'body' => 'First Article Body',
  696. 'author_id' => 1,
  697. 'published' => 'Y',
  698. '_matchingData' => [
  699. 'Tags' => [
  700. 'id' => 2,
  701. 'name' => 'tag2',
  702. ],
  703. 'ArticlesTags' => ['article_id' => 1, 'tag_id' => 2]
  704. ]
  705. ]
  706. ];
  707. $this->assertEquals($expected, $results);
  708. }
  709. /**
  710. * Tests that it is possible to filter by deep associations
  711. *
  712. * @return void
  713. */
  714. public function testMatchingDotNotation()
  715. {
  716. $query = new Query($this->connection, $this->table);
  717. $table = TableRegistry::get('authors');
  718. TableRegistry::get('articles');
  719. $table->hasMany('articles');
  720. TableRegistry::get('articles')->belongsToMany('tags');
  721. $results = $query->repository($table)
  722. ->select()
  723. ->hydrate(false)
  724. ->matching('articles.tags', function ($q) {
  725. return $q->where(['tags.id' => 2]);
  726. })
  727. ->toArray();
  728. $expected = [
  729. [
  730. 'id' => 1,
  731. 'name' => 'mariano',
  732. '_matchingData' => [
  733. 'tags' => [
  734. 'id' => 2,
  735. 'name' => 'tag2',
  736. ],
  737. 'articles' => [
  738. 'id' => 1,
  739. 'author_id' => 1,
  740. 'title' => 'First Article',
  741. 'body' => 'First Article Body',
  742. 'published' => 'Y'
  743. ],
  744. 'ArticlesTags' => [
  745. 'article_id' => 1,
  746. 'tag_id' => 2
  747. ]
  748. ]
  749. ]
  750. ];
  751. $this->assertEquals($expected, $results);
  752. }
  753. /**
  754. * Test setResult()
  755. *
  756. * @return void
  757. */
  758. public function testSetResult()
  759. {
  760. $query = new Query($this->connection, $this->table);
  761. $stmt = $this->getMock('Cake\Database\StatementInterface');
  762. $results = new ResultSet($query, $stmt);
  763. $query->setResult($results);
  764. $this->assertSame($results, $query->all());
  765. }
  766. /**
  767. * Tests that applying array options to a query will convert them
  768. * to equivalent function calls with the correspondent array values
  769. *
  770. * @return void
  771. */
  772. public function testApplyOptions()
  773. {
  774. $this->table->belongsTo('articles');
  775. $typeMap = new TypeMap([
  776. 'foo.id' => 'integer',
  777. 'id' => 'integer',
  778. 'articles.id' => 'integer',
  779. 'articles.author_id' => 'integer',
  780. 'author_id' => 'integer',
  781. 'articles.title' => 'string',
  782. 'title' => 'string',
  783. 'articles.body' => 'text',
  784. 'body' => 'text',
  785. 'articles.published' => 'string',
  786. 'published' => 'string',
  787. ]);
  788. $options = [
  789. 'fields' => ['field_a', 'field_b'],
  790. 'conditions' => ['field_a' => 1, 'field_b' => 'something'],
  791. 'limit' => 1,
  792. 'order' => ['a' => 'ASC'],
  793. 'offset' => 5,
  794. 'group' => ['field_a'],
  795. 'having' => ['field_a >' => 100],
  796. 'contain' => ['articles'],
  797. 'join' => ['table_a' => ['conditions' => ['a > b']]]
  798. ];
  799. $query = new Query($this->connection, $this->table);
  800. $query->applyOptions($options);
  801. $this->assertEquals(['field_a', 'field_b'], $query->clause('select'));
  802. $expected = new QueryExpression($options['conditions'], $typeMap);
  803. $result = $query->clause('where');
  804. $this->assertEquals($expected, $result);
  805. $this->assertEquals(1, $query->clause('limit'));
  806. $expected = new QueryExpression(['a > b'], $typeMap);
  807. $result = $query->clause('join');
  808. $this->assertEquals([
  809. 'table_a' => ['alias' => 'table_a', 'type' => 'INNER', 'conditions' => $expected]
  810. ], $result);
  811. $expected = new OrderByExpression(['a' => 'ASC']);
  812. $this->assertEquals($expected, $query->clause('order'));
  813. $this->assertEquals(5, $query->clause('offset'));
  814. $this->assertEquals(['field_a'], $query->clause('group'));
  815. $expected = new QueryExpression($options['having'], $typeMap);
  816. $this->assertEquals($expected, $query->clause('having'));
  817. $expected = ['articles' => []];
  818. $this->assertEquals($expected, $query->contain());
  819. }
  820. /**
  821. * Test that page is applied after limit.
  822. *
  823. * @return void
  824. */
  825. public function testApplyOptionsPageIsLast()
  826. {
  827. $query = new Query($this->connection, $this->table);
  828. $opts = [
  829. 'page' => 3,
  830. 'limit' => 5
  831. ];
  832. $query->applyOptions($opts);
  833. $this->assertEquals(5, $query->clause('limit'));
  834. $this->assertEquals(10, $query->clause('offset'));
  835. }
  836. /**
  837. * ApplyOptions should ignore null values.
  838. *
  839. * @return void
  840. */
  841. public function testApplyOptionsIgnoreNull()
  842. {
  843. $options = [
  844. 'fields' => null,
  845. ];
  846. $query = new Query($this->connection, $this->table);
  847. $query->applyOptions($options);
  848. $this->assertEquals([], $query->clause('select'));
  849. }
  850. /**
  851. * Tests getOptions() method
  852. *
  853. * @return void
  854. */
  855. public function testGetOptions()
  856. {
  857. $options = ['doABarrelRoll' => true, 'fields' => ['id', 'name']];
  858. $query = new Query($this->connection, $this->table);
  859. $query->applyOptions($options);
  860. $expected = ['doABarrelRoll' => true];
  861. $this->assertEquals($expected, $query->getOptions());
  862. $expected = ['doABarrelRoll' => false, 'doAwesome' => true];
  863. $query->applyOptions($expected);
  864. $this->assertEquals($expected, $query->getOptions());
  865. }
  866. /**
  867. * Tests registering mappers with mapReduce()
  868. *
  869. * @return void
  870. */
  871. public function testMapReduceOnlyMapper()
  872. {
  873. $mapper1 = function () {
  874. };
  875. $mapper2 = function () {
  876. };
  877. $query = new Query($this->connection, $this->table);
  878. $this->assertSame($query, $query->mapReduce($mapper1));
  879. $this->assertEquals(
  880. [['mapper' => $mapper1, 'reducer' => null]],
  881. $query->mapReduce()
  882. );
  883. $this->assertEquals($query, $query->mapReduce($mapper2));
  884. $result = $query->mapReduce();
  885. $this->assertSame(
  886. [
  887. ['mapper' => $mapper1, 'reducer' => null],
  888. ['mapper' => $mapper2, 'reducer' => null]
  889. ],
  890. $result
  891. );
  892. }
  893. /**
  894. * Tests registering mappers and reducers with mapReduce()
  895. *
  896. * @return void
  897. */
  898. public function testMapReduceBothMethods()
  899. {
  900. $mapper1 = function () {
  901. };
  902. $mapper2 = function () {
  903. };
  904. $reducer1 = function () {
  905. };
  906. $reducer2 = function () {
  907. };
  908. $query = new Query($this->connection, $this->table);
  909. $this->assertSame($query, $query->mapReduce($mapper1, $reducer1));
  910. $this->assertEquals(
  911. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  912. $query->mapReduce()
  913. );
  914. $this->assertSame($query, $query->mapReduce($mapper2, $reducer2));
  915. $this->assertEquals(
  916. [
  917. ['mapper' => $mapper1, 'reducer' => $reducer1],
  918. ['mapper' => $mapper2, 'reducer' => $reducer2]
  919. ],
  920. $query->mapReduce()
  921. );
  922. }
  923. /**
  924. * Tests that it is possible to overwrite previous map reducers
  925. *
  926. * @return void
  927. */
  928. public function testOverwriteMapReduce()
  929. {
  930. $mapper1 = function () {
  931. };
  932. $mapper2 = function () {
  933. };
  934. $reducer1 = function () {
  935. };
  936. $reducer2 = function () {
  937. };
  938. $query = new Query($this->connection, $this->table);
  939. $this->assertEquals($query, $query->mapReduce($mapper1, $reducer1));
  940. $this->assertEquals(
  941. [['mapper' => $mapper1, 'reducer' => $reducer1]],
  942. $query->mapReduce()
  943. );
  944. $this->assertEquals($query, $query->mapReduce($mapper2, $reducer2, true));
  945. $this->assertEquals(
  946. [['mapper' => $mapper2, 'reducer' => $reducer2]],
  947. $query->mapReduce()
  948. );
  949. }
  950. /**
  951. * Tests that multiple map reducers can be stacked
  952. *
  953. * @return void
  954. */
  955. public function testResultsAreWrappedInMapReduce()
  956. {
  957. $table = TableRegistry::get('articles', ['table' => 'articles']);
  958. $query = new Query($this->connection, $table);
  959. $query->select(['a' => 'id'])->limit(2)->order(['id' => 'ASC']);
  960. $query->mapReduce(function ($v, $k, $mr) {
  961. $mr->emit($v['a']);
  962. });
  963. $query->mapReduce(
  964. function ($v, $k, $mr) {
  965. $mr->emitIntermediate($v, $k);
  966. },
  967. function ($v, $k, $mr) {
  968. $mr->emit($v[0] + 1);
  969. }
  970. );
  971. $this->assertEquals([2, 3], iterator_to_array($query->all()));
  972. }
  973. /**
  974. * Tests first() method when the query has not been executed before
  975. *
  976. * @return void
  977. */
  978. public function testFirstDirtyQuery()
  979. {
  980. $table = TableRegistry::get('articles', ['table' => 'articles']);
  981. $query = new Query($this->connection, $table);
  982. $result = $query->select(['id'])->hydrate(false)->first();
  983. $this->assertEquals(['id' => 1], $result);
  984. $this->assertEquals(1, $query->clause('limit'));
  985. $result = $query->select(['id'])->first();
  986. $this->assertEquals(['id' => 1], $result);
  987. }
  988. /**
  989. * Tests that first can be called again on an already executed query
  990. *
  991. * @return void
  992. */
  993. public function testFirstCleanQuery()
  994. {
  995. $table = TableRegistry::get('articles', ['table' => 'articles']);
  996. $query = new Query($this->connection, $table);
  997. $query->select(['id'])->toArray();
  998. $first = $query->hydrate(false)->first();
  999. $this->assertEquals(['id' => 1], $first);
  1000. $this->assertEquals(1, $query->clause('limit'));
  1001. }
  1002. /**
  1003. * Tests that first() will not execute the same query twice
  1004. *
  1005. * @return void
  1006. */
  1007. public function testFirstSameResult()
  1008. {
  1009. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1010. $query = new Query($this->connection, $table);
  1011. $query->select(['id'])->toArray();
  1012. $first = $query->hydrate(false)->first();
  1013. $resultSet = $query->all();
  1014. $this->assertEquals(['id' => 1], $first);
  1015. $this->assertSame($resultSet, $query->all());
  1016. }
  1017. /**
  1018. * Tests that first can be called against a query with a mapReduce
  1019. *
  1020. * @return void
  1021. */
  1022. public function testFirstMapReduce()
  1023. {
  1024. $map = function ($row, $key, $mapReduce) {
  1025. $mapReduce->emitIntermediate($row['id'], 'id');
  1026. };
  1027. $reduce = function ($values, $key, $mapReduce) {
  1028. $mapReduce->emit(array_sum($values));
  1029. };
  1030. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1031. $query = new Query($this->connection, $table);
  1032. $query->select(['id'])
  1033. ->hydrate(false)
  1034. ->mapReduce($map, $reduce);
  1035. $first = $query->first();
  1036. $this->assertEquals(1, $first);
  1037. }
  1038. /**
  1039. * Tests that first can be called on an unbuffered query
  1040. *
  1041. * @return void
  1042. */
  1043. public function testFirstUnbuffered()
  1044. {
  1045. $table = TableRegistry::get('Articles');
  1046. $query = new Query($this->connection, $table);
  1047. $query->select(['id']);
  1048. $first = $query->hydrate(false)
  1049. ->bufferResults(false)->first();
  1050. $this->assertEquals(['id' => 1], $first);
  1051. }
  1052. /**
  1053. * Testing hydrating a result set into Entity objects
  1054. *
  1055. * @return void
  1056. */
  1057. public function testHydrateSimple()
  1058. {
  1059. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1060. $query = new Query($this->connection, $table);
  1061. $results = $query->select()->toArray();
  1062. $this->assertCount(3, $results);
  1063. foreach ($results as $r) {
  1064. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1065. }
  1066. $first = $results[0];
  1067. $this->assertEquals(1, $first->id);
  1068. $this->assertEquals(1, $first->author_id);
  1069. $this->assertEquals('First Article', $first->title);
  1070. $this->assertEquals('First Article Body', $first->body);
  1071. $this->assertEquals('Y', $first->published);
  1072. }
  1073. /**
  1074. * Tests that has many results are also hydrated correctly
  1075. *
  1076. * @return void
  1077. */
  1078. public function testHydrateHasMany()
  1079. {
  1080. $table = TableRegistry::get('authors');
  1081. TableRegistry::get('articles');
  1082. $table->hasMany('articles', [
  1083. 'propertyName' => 'articles',
  1084. 'sort' => ['articles.id' => 'asc']
  1085. ]);
  1086. $query = new Query($this->connection, $table);
  1087. $results = $query->select()
  1088. ->contain('articles')
  1089. ->toArray();
  1090. $first = $results[0];
  1091. foreach ($first->articles as $r) {
  1092. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1093. }
  1094. $this->assertCount(2, $first->articles);
  1095. $expected = [
  1096. 'id' => 1,
  1097. 'title' => 'First Article',
  1098. 'body' => 'First Article Body',
  1099. 'author_id' => 1,
  1100. 'published' => 'Y',
  1101. ];
  1102. $this->assertEquals($expected, $first->articles[0]->toArray());
  1103. $expected = [
  1104. 'id' => 3,
  1105. 'title' => 'Third Article',
  1106. 'author_id' => 1,
  1107. 'body' => 'Third Article Body',
  1108. 'published' => 'Y',
  1109. ];
  1110. $this->assertEquals($expected, $first->articles[1]->toArray());
  1111. }
  1112. /**
  1113. * Tests that belongsToMany associations are also correctly hydrated
  1114. *
  1115. * @return void
  1116. */
  1117. public function testHydrateBelongsToMany()
  1118. {
  1119. $table = TableRegistry::get('Articles');
  1120. TableRegistry::get('Tags');
  1121. TableRegistry::get('ArticlesTags', [
  1122. 'table' => 'articles_tags'
  1123. ]);
  1124. $table->belongsToMany('Tags');
  1125. $query = new Query($this->connection, $table);
  1126. $results = $query
  1127. ->select()
  1128. ->contain('Tags')
  1129. ->toArray();
  1130. $first = $results[0];
  1131. foreach ($first->tags as $r) {
  1132. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1133. }
  1134. $this->assertCount(2, $first->tags);
  1135. $expected = [
  1136. 'id' => 1,
  1137. 'name' => 'tag1',
  1138. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1139. ];
  1140. $this->assertEquals($expected, $first->tags[0]->toArray());
  1141. $expected = [
  1142. 'id' => 2,
  1143. 'name' => 'tag2',
  1144. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1145. ];
  1146. $this->assertEquals($expected, $first->tags[1]->toArray());
  1147. }
  1148. /**
  1149. * Tests that belongsToMany associations are also correctly hydrated
  1150. *
  1151. * @return void
  1152. */
  1153. public function testFormatResultsBelongsToMany()
  1154. {
  1155. $table = TableRegistry::get('Articles');
  1156. TableRegistry::get('Tags');
  1157. $articlesTags = TableRegistry::get('ArticlesTags', [
  1158. 'table' => 'articles_tags'
  1159. ]);
  1160. $table->belongsToMany('Tags');
  1161. $articlesTags
  1162. ->eventManager()
  1163. ->attach(function ($event, $query) {
  1164. $query->formatResults(function ($results) {
  1165. return $results;
  1166. });
  1167. }, 'Model.beforeFind');
  1168. $query = new Query($this->connection, $table);
  1169. $results = $query
  1170. ->select()
  1171. ->contain('Tags')
  1172. ->toArray();
  1173. $first = $results[0];
  1174. foreach ($first->tags as $r) {
  1175. $this->assertInstanceOf('Cake\ORM\Entity', $r);
  1176. }
  1177. $this->assertCount(2, $first->tags);
  1178. $expected = [
  1179. 'id' => 1,
  1180. 'name' => 'tag1',
  1181. '_joinData' => ['article_id' => 1, 'tag_id' => 1]
  1182. ];
  1183. $this->assertEquals($expected, $first->tags[0]->toArray());
  1184. $expected = [
  1185. 'id' => 2,
  1186. 'name' => 'tag2',
  1187. '_joinData' => ['article_id' => 1, 'tag_id' => 2]
  1188. ];
  1189. $this->assertEquals($expected, $first->tags[1]->toArray());
  1190. }
  1191. /**
  1192. * Tests that belongsTo relations are correctly hydrated
  1193. *
  1194. * @dataProvider strategiesProviderBelongsTo
  1195. * @return void
  1196. */
  1197. public function testHydrateBelongsTo($strategy)
  1198. {
  1199. $table = TableRegistry::get('articles');
  1200. TableRegistry::get('authors');
  1201. $table->belongsTo('authors', ['strategy' => $strategy]);
  1202. $query = new Query($this->connection, $table);
  1203. $results = $query->select()
  1204. ->contain('authors')
  1205. ->order(['articles.id' => 'asc'])
  1206. ->toArray();
  1207. $this->assertCount(3, $results);
  1208. $first = $results[0];
  1209. $this->assertInstanceOf('Cake\ORM\Entity', $first->author);
  1210. $expected = ['id' => 1, 'name' => 'mariano'];
  1211. $this->assertEquals($expected, $first->author->toArray());
  1212. }
  1213. /**
  1214. * Tests that deeply nested associations are also hydrated correctly
  1215. *
  1216. * @dataProvider strategiesProviderBelongsTo
  1217. * @return void
  1218. */
  1219. public function testHydrateDeep($strategy)
  1220. {
  1221. $table = TableRegistry::get('authors');
  1222. $article = TableRegistry::get('articles');
  1223. $table->hasMany('articles', [
  1224. 'propertyName' => 'articles',
  1225. 'sort' => ['articles.id' => 'asc']
  1226. ]);
  1227. $article->belongsTo('authors', ['strategy' => $strategy]);
  1228. $query = new Query($this->connection, $table);
  1229. $results = $query->select()
  1230. ->contain(['articles' => ['authors']])
  1231. ->toArray();
  1232. $this->assertCount(4, $results);
  1233. $first = $results[0];
  1234. $this->assertInstanceOf('Cake\ORM\Entity', $first->articles[0]->author);
  1235. $expected = ['id' => 1, 'name' => 'mariano'];
  1236. $this->assertEquals($expected, $first->articles[0]->author->toArray());
  1237. $this->assertTrue(isset($results[3]->articles));
  1238. }
  1239. /**
  1240. * Tests that it is possible to use a custom entity class
  1241. *
  1242. * @return void
  1243. */
  1244. public function testHydrateCustomObject()
  1245. {
  1246. $class = $this->getMockClass('\Cake\ORM\Entity', ['fakeMethod']);
  1247. $table = TableRegistry::get('articles', [
  1248. 'table' => 'articles',
  1249. 'entityClass' => '\\' . $class
  1250. ]);
  1251. $query = new Query($this->connection, $table);
  1252. $results = $query->select()->toArray();
  1253. $this->assertCount(3, $results);
  1254. foreach ($results as $r) {
  1255. $this->assertInstanceOf($class, $r);
  1256. }
  1257. $first = $results[0];
  1258. $this->assertEquals(1, $first->id);
  1259. $this->assertEquals(1, $first->author_id);
  1260. $this->assertEquals('First Article', $first->title);
  1261. $this->assertEquals('First Article Body', $first->body);
  1262. $this->assertEquals('Y', $first->published);
  1263. }
  1264. /**
  1265. * Tests that has many results are also hydrated correctly
  1266. * when specified a custom entity class
  1267. *
  1268. * @return void
  1269. */
  1270. public function testHydrateHasManyCustomEntity()
  1271. {
  1272. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1273. $articleEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1274. $table = TableRegistry::get('authors', [
  1275. 'entityClass' => '\\' . $authorEntity
  1276. ]);
  1277. TableRegistry::get('articles', [
  1278. 'entityClass' => '\\' . $articleEntity
  1279. ]);
  1280. $table->hasMany('articles', [
  1281. 'propertyName' => 'articles',
  1282. 'sort' => ['articles.id' => 'asc']
  1283. ]);
  1284. $query = new Query($this->connection, $table);
  1285. $results = $query->select()
  1286. ->contain('articles')
  1287. ->toArray();
  1288. $first = $results[0];
  1289. $this->assertInstanceOf($authorEntity, $first);
  1290. foreach ($first->articles as $r) {
  1291. $this->assertInstanceOf($articleEntity, $r);
  1292. }
  1293. $this->assertCount(2, $first->articles);
  1294. $expected = [
  1295. 'id' => 1,
  1296. 'title' => 'First Article',
  1297. 'body' => 'First Article Body',
  1298. 'author_id' => 1,
  1299. 'published' => 'Y',
  1300. ];
  1301. $this->assertEquals($expected, $first->articles[0]->toArray());
  1302. }
  1303. /**
  1304. * Tests that belongsTo relations are correctly hydrated into a custom entity class
  1305. *
  1306. * @return void
  1307. */
  1308. public function testHydrateBelongsToCustomEntity()
  1309. {
  1310. $authorEntity = $this->getMockClass('\Cake\ORM\Entity', ['foo']);
  1311. $table = TableRegistry::get('articles');
  1312. TableRegistry::get('authors', [
  1313. 'entityClass' => '\\' . $authorEntity
  1314. ]);
  1315. $table->belongsTo('authors');
  1316. $query = new Query($this->connection, $table);
  1317. $results = $query->select()
  1318. ->contain('authors')
  1319. ->order(['articles.id' => 'asc'])
  1320. ->toArray();
  1321. $first = $results[0];
  1322. $this->assertInstanceOf($authorEntity, $first->author);
  1323. }
  1324. /**
  1325. * Test getting counts from queries.
  1326. *
  1327. * @return void
  1328. */
  1329. public function testCount()
  1330. {
  1331. $table = TableRegistry::get('articles');
  1332. $result = $table->find('all')->count();
  1333. $this->assertSame(3, $result);
  1334. $query = $table->find('all')
  1335. ->where(['id >' => 1])
  1336. ->limit(1);
  1337. $result = $query->count();
  1338. $this->assertSame(2, $result);
  1339. $result = $query->all();
  1340. $this->assertCount(1, $result);
  1341. $this->assertEquals(2, $result->first()->id);
  1342. }
  1343. /**
  1344. * Test getting counts from queries with contain.
  1345. *
  1346. * @return void
  1347. */
  1348. public function testCountWithContain()
  1349. {
  1350. $table = TableRegistry::get('Articles');
  1351. $table->belongsTo('Authors');
  1352. $result = $table->find('all')
  1353. ->contain([
  1354. 'Authors' => [
  1355. 'fields' => ['name']
  1356. ]
  1357. ])
  1358. ->count();
  1359. $this->assertSame(3, $result);
  1360. }
  1361. /**
  1362. * Test getting counts from queries with contain.
  1363. *
  1364. * @return void
  1365. */
  1366. public function testCountWithSubselect()
  1367. {
  1368. $table = TableRegistry::get('Articles');
  1369. $table->belongsTo('Authors');
  1370. $table->hasMany('ArticlesTags');
  1371. $counter = $table->ArticlesTags->find();
  1372. $counter->select([
  1373. 'total' => $counter->func()->count('*')
  1374. ])
  1375. ->where([
  1376. 'ArticlesTags.tag_id' => 1,
  1377. 'ArticlesTags.article_id' => new IdentifierExpression('Articles.id')
  1378. ]);
  1379. $result = $table->find('all')
  1380. ->select([
  1381. 'Articles.title',
  1382. 'tag_count' => $counter
  1383. ])
  1384. ->matching('Authors', function ($q) {
  1385. return $q->where(['Authors.id' => 1]);
  1386. })
  1387. ->count();
  1388. $this->assertSame(2, $result);
  1389. }
  1390. /**
  1391. * Test getting counts with complex fields.
  1392. *
  1393. * @return void
  1394. */
  1395. public function testCountWithExpressions()
  1396. {
  1397. $table = TableRegistry::get('Articles');
  1398. $query = $table->find();
  1399. $query->select([
  1400. 'title' => $query->func()->concat(
  1401. ['title' => 'literal', 'test'],
  1402. ['string']
  1403. ),
  1404. ]);
  1405. $query->where(['id' => 1]);
  1406. $this->assertCount(1, $query->all());
  1407. $this->assertEquals(1, $query->count());
  1408. }
  1409. /**
  1410. * test count with a beforeFind.
  1411. *
  1412. * @return void
  1413. */
  1414. public function testCountBeforeFind()
  1415. {
  1416. $table = TableRegistry::get('Articles');
  1417. $table->hasMany('Comments');
  1418. $table->eventManager()
  1419. ->attach(function ($event, $query) {
  1420. $query
  1421. ->limit(1)
  1422. ->order(['Articles.title' => 'DESC']);
  1423. }, 'Model.beforeFind');
  1424. $query = $table->find();
  1425. $result = $query->count();
  1426. $this->assertSame(3, $result);
  1427. }
  1428. /**
  1429. * Test that count() returns correct results with group by.
  1430. *
  1431. * @return void
  1432. */
  1433. public function testCountWithGroup()
  1434. {
  1435. $table = TableRegistry::get('articles');
  1436. $query = $table->find('all');
  1437. $query->select(['author_id', 's' => $query->func()->sum('id')])
  1438. ->group(['author_id']);
  1439. $result = $query->count();
  1440. $this->assertEquals(2, $result);
  1441. }
  1442. /**
  1443. * Tests that it is possible to provide a callback for calculating the count
  1444. * of a query
  1445. *
  1446. * @return void
  1447. */
  1448. public function testCountWithCustomCounter()
  1449. {
  1450. $table = TableRegistry::get('articles');
  1451. $query = $table->find('all');
  1452. $query
  1453. ->select(['author_id', 's' => $query->func()->sum('id')])
  1454. ->where(['id >' => 2])
  1455. ->group(['author_id'])
  1456. ->counter(function ($q) use ($query) {
  1457. $this->assertNotSame($q, $query);
  1458. return $q->select([], true)->group([], true)->count();
  1459. });
  1460. $result = $query->count();
  1461. $this->assertEquals(1, $result);
  1462. }
  1463. /**
  1464. * Test update method.
  1465. *
  1466. * @return void
  1467. */
  1468. public function testUpdate()
  1469. {
  1470. $table = TableRegistry::get('articles');
  1471. $result = $table->query()
  1472. ->update()
  1473. ->set(['title' => 'First'])
  1474. ->execute();
  1475. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1476. $this->assertTrue($result->rowCount() > 0);
  1477. }
  1478. /**
  1479. * Test update method.
  1480. *
  1481. * @return void
  1482. */
  1483. public function testUpdateWithTableExpression()
  1484. {
  1485. $this->skipIf(!$this->connection->driver() instanceof \Cake\Database\Driver\Mysql);
  1486. $table = TableRegistry::get('articles');
  1487. $query = $table->query();
  1488. $result = $query->update($query->newExpr('articles, authors'))
  1489. ->set(['title' => 'First'])
  1490. ->where(['articles.author_id = authors.id'])
  1491. ->andWhere(['authors.name' => 'mariano'])
  1492. ->execute();
  1493. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1494. $this->assertTrue($result->rowCount() > 0);
  1495. }
  1496. /**
  1497. * Test insert method.
  1498. *
  1499. * @return void
  1500. */
  1501. public function testInsert()
  1502. {
  1503. $table = TableRegistry::get('articles');
  1504. $result = $table->query()
  1505. ->insert(['title'])
  1506. ->values(['title' => 'First'])
  1507. ->values(['title' => 'Second'])
  1508. ->execute();
  1509. $result->closeCursor();
  1510. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1511. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  1512. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  1513. $this->assertEquals(2, $result->rowCount());
  1514. } else {
  1515. $this->assertEquals(-1, $result->rowCount());
  1516. }
  1517. }
  1518. /**
  1519. * Test delete method.
  1520. *
  1521. * @return void
  1522. */
  1523. public function testDelete()
  1524. {
  1525. $table = TableRegistry::get('articles');
  1526. $result = $table->query()
  1527. ->delete()
  1528. ->where(['id >=' => 1])
  1529. ->execute();
  1530. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1531. $this->assertTrue($result->rowCount() > 0);
  1532. }
  1533. /**
  1534. * Provides a list of collection methods that can be proxied
  1535. * from the query
  1536. *
  1537. * @return array
  1538. */
  1539. public function collectionMethodsProvider()
  1540. {
  1541. $identity = function ($a) {
  1542. return $a;
  1543. };
  1544. return [
  1545. ['filter', $identity],
  1546. ['reject', $identity],
  1547. ['every', $identity],
  1548. ['some', $identity],
  1549. ['contains', $identity],
  1550. ['map', $identity],
  1551. ['reduce', $identity],
  1552. ['extract', $identity],
  1553. ['max', $identity],
  1554. ['min', $identity],
  1555. ['sortBy', $identity],
  1556. ['groupBy', $identity],
  1557. ['countBy', $identity],
  1558. ['shuffle', $identity],
  1559. ['sample', $identity],
  1560. ['take', 1],
  1561. ['append', new \ArrayIterator],
  1562. ['compile', 1],
  1563. ];
  1564. }
  1565. /**
  1566. * Tests that query can proxy collection methods
  1567. *
  1568. * @dataProvider collectionMethodsProvider
  1569. * @return void
  1570. */
  1571. public function testCollectionProxy($method, $arg)
  1572. {
  1573. $query = $this->getMock(
  1574. '\Cake\ORM\Query',
  1575. ['all'],
  1576. [$this->connection, $this->table]
  1577. );
  1578. $query->select();
  1579. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1580. $query->expects($this->once())
  1581. ->method('all')
  1582. ->will($this->returnValue($resultSet));
  1583. $resultSet->expects($this->once())
  1584. ->method($method)
  1585. ->with($arg, 'extra')
  1586. ->will($this->returnValue(new \Cake\Collection\Collection([])));
  1587. $this->assertInstanceOf(
  1588. '\Cake\Collection\Collection',
  1589. $query->{$method}($arg, 'extra')
  1590. );
  1591. }
  1592. /**
  1593. * Tests that calling an inexistent method in query throws an
  1594. * exception
  1595. *
  1596. * @expectedException \BadMethodCallException
  1597. * @expectedExceptionMessage Unknown method "derpFilter"
  1598. * @return void
  1599. */
  1600. public function testCollectionProxyBadMethod()
  1601. {
  1602. TableRegistry::get('articles')->find('all')->derpFilter();
  1603. }
  1604. /**
  1605. * cache() should fail on non select queries.
  1606. *
  1607. * @expectedException \RuntimeException
  1608. * @return void
  1609. */
  1610. public function testCacheErrorOnNonSelect()
  1611. {
  1612. $table = TableRegistry::get('articles', ['table' => 'articles']);
  1613. $query = new Query($this->connection, $table);
  1614. $query->insert(['test']);
  1615. $query->cache('my_key');
  1616. }
  1617. /**
  1618. * Integration test for query caching.
  1619. *
  1620. * @return void
  1621. */
  1622. public function testCacheReadIntegration()
  1623. {
  1624. $query = $this->getMock(
  1625. '\Cake\ORM\Query',
  1626. ['execute'],
  1627. [$this->connection, $this->table]
  1628. );
  1629. $resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);
  1630. $query->expects($this->never())
  1631. ->method('execute');
  1632. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1633. $cacher->expects($this->once())
  1634. ->method('read')
  1635. ->with('my_key')
  1636. ->will($this->returnValue($resultSet));
  1637. $query->cache('my_key', $cacher)
  1638. ->where(['id' => 1]);
  1639. $results = $query->all();
  1640. $this->assertSame($resultSet, $results);
  1641. }
  1642. /**
  1643. * Integration test for query caching.
  1644. *
  1645. * @return void
  1646. */
  1647. public function testCacheWriteIntegration()
  1648. {
  1649. $table = TableRegistry::get('Articles');
  1650. $query = new Query($this->connection, $table);
  1651. $query->select(['id', 'title']);
  1652. $cacher = $this->getMock('Cake\Cache\CacheEngine');
  1653. $cacher->expects($this->once())
  1654. ->method('write')
  1655. ->with(
  1656. 'my_key',
  1657. $this->isInstanceOf('Cake\Datasource\ResultSetInterface')
  1658. );
  1659. $query->cache('my_key', $cacher)
  1660. ->where(['id' => 1]);
  1661. $query->all();
  1662. }
  1663. /**
  1664. * Integration test for query caching usigna real cache engine and
  1665. * a formatResults callback
  1666. *
  1667. * @return void
  1668. */
  1669. public function testCacheIntegrationWithFormatResults()
  1670. {
  1671. $table = TableRegistry::get('Articles');
  1672. $query = new Query($this->connection, $table);
  1673. $cacher = new \Cake\Cache\Engine\FileEngine();
  1674. $cacher->init();
  1675. $query
  1676. ->select(['id', 'title'])
  1677. ->formatResults(function ($results) {
  1678. return $results->combine('id', 'title');
  1679. })
  1680. ->cache('my_key', $cacher);
  1681. $expected = $query->toArray();
  1682. $query = new Query($this->connection, $table);
  1683. $results = $query->cache('my_key', $cacher)->toArray();
  1684. $this->assertSame($expected, $results);
  1685. }
  1686. /**
  1687. * Test overwriting the contained associations.
  1688. *
  1689. * @return void
  1690. */
  1691. public function testContainOverwrite()
  1692. {
  1693. $table = TableRegistry::get('Articles');
  1694. $table->hasMany('Comments');
  1695. $table->belongsTo('Authors');
  1696. $query = $table->find();
  1697. $query->contain(['Comments']);
  1698. $this->assertEquals(['Comments'], array_keys($query->contain()));
  1699. $query->contain(['Authors'], true);
  1700. $this->assertEquals(['Authors'], array_keys($query->contain()));
  1701. $query->contain(['Comments', 'Authors'], true);
  1702. $this->assertEquals(['Comments', 'Authors'], array_keys($query->contain()));
  1703. }
  1704. /**
  1705. * Integration test to show filtering associations using contain and a closure
  1706. *
  1707. * @return void
  1708. */
  1709. public function testContainWithClosure()
  1710. {
  1711. $table = TableRegistry::get('authors');
  1712. $table->hasMany('articles');
  1713. $query = new Query($this->connection, $table);
  1714. $query
  1715. ->select()
  1716. ->contain(['articles' => function ($q) {
  1717. return $q->where(['articles.id' => 1]);
  1718. }]);
  1719. $ids = [];
  1720. foreach ($query as $entity) {
  1721. foreach ((array)$entity->articles as $article) {
  1722. $ids[] = $article->id;
  1723. }
  1724. }
  1725. $this->assertEquals([1], array_unique($ids));
  1726. }
  1727. /**
  1728. * Integration test to ensure that filtering associations with the queryBuilder
  1729. * option works.
  1730. *
  1731. * @expectedException \RuntimeException
  1732. * @return void
  1733. */
  1734. public function testContainWithQueryBuilderHasManyError()
  1735. {
  1736. $table = TableRegistry::get('Authors');
  1737. $table->hasMany('Articles');
  1738. $query = new Query($this->connection, $table);
  1739. $query->select()
  1740. ->contain([
  1741. 'Articles' => [
  1742. 'foreignKey' => false,
  1743. 'queryBuilder' => function ($q) {
  1744. return $q->where(['articles.id' => 1]);
  1745. }
  1746. ]
  1747. ]);
  1748. $query->toArray();
  1749. }
  1750. /**
  1751. * Integration test to ensure that filtering associations with the queryBuilder
  1752. * option works.
  1753. *
  1754. * @return void
  1755. */
  1756. public function testContainWithQueryBuilderJoinableAssociation()
  1757. {
  1758. $table = TableRegistry::get('Authors');
  1759. $table->hasOne('Articles');
  1760. $query = new Query($this->connection, $table);
  1761. $query->select()
  1762. ->contain([
  1763. 'Articles' => [
  1764. 'foreignKey' => false,
  1765. 'queryBuilder' => function ($q) {
  1766. return $q->where(['Articles.id' => 1]);
  1767. }
  1768. ]
  1769. ]);
  1770. $result = $query->toArray();
  1771. $this->assertEquals(1, $result[0]->article->id);
  1772. $this->assertEquals(1, $result[1]->article->id);
  1773. $articles = TableRegistry::get('Articles');
  1774. $articles->belongsTo('Authors');
  1775. $query = new Query($this->connection, $articles);
  1776. $query->select()
  1777. ->contain([
  1778. 'Authors' => [
  1779. 'foreignKey' => false,
  1780. 'queryBuilder' => function ($q) {
  1781. return $q->where(['Authors.id' => 1]);
  1782. }
  1783. ]
  1784. ]);
  1785. $result = $query->toArray();
  1786. $this->assertEquals(1, $result[0]->author->id);
  1787. }
  1788. /**
  1789. * Test containing associations that have empty conditions.
  1790. *
  1791. * @return void
  1792. */
  1793. public function testContainAssociationWithEmptyConditions()
  1794. {
  1795. $articles = TableRegistry::get('Articles');
  1796. $articles->belongsTo('Authors', [
  1797. 'conditions' => function ($exp, $query) {
  1798. return $exp;
  1799. }
  1800. ]);
  1801. $query = $articles->find('all')->contain(['Authors']);
  1802. $result = $query->toArray();
  1803. $this->assertCount(3, $result);
  1804. }
  1805. /**
  1806. * Tests the formatResults method
  1807. *
  1808. * @return void
  1809. */
  1810. public function testFormatResults()
  1811. {
  1812. $callback1 = function () {
  1813. };
  1814. $callback2 = function () {
  1815. };
  1816. $table = TableRegistry::get('authors');
  1817. $query = new Query($this->connection, $table);
  1818. $this->assertSame($query, $query->formatResults($callback1));
  1819. $this->assertSame([$callback1], $query->formatResults());
  1820. $this->assertSame($query, $query->formatResults($callback2));
  1821. $this->assertSame([$callback1, $callback2], $query->formatResults());
  1822. $query->formatResults($callback2, true);
  1823. $this->assertSame([$callback2], $query->formatResults());
  1824. $query->formatResults(null, true);
  1825. $this->assertSame([], $query->formatResults());
  1826. $query->formatResults($callback1);
  1827. $query->formatResults($callback2, $query::PREPEND);
  1828. $this->assertSame([$callback2, $callback1], $query->formatResults());
  1829. }
  1830. /**
  1831. * Test fetching results from a qurey with a custom formatter
  1832. *
  1833. * @return void
  1834. */
  1835. public function testQueryWithFormatter()
  1836. {
  1837. $table = TableRegistry::get('authors');
  1838. $query = new Query($this->connection, $table);
  1839. $query->select()->formatResults(function ($results) {
  1840. $this->assertInstanceOf('Cake\ORM\ResultSet', $results);
  1841. return $results->indexBy('id');
  1842. });
  1843. $this->assertEquals([1, 2, 3, 4], array_keys($query->toArray()));
  1844. }
  1845. /**
  1846. * Test fetching results from a qurey with a two custom formatters
  1847. *
  1848. * @return void
  1849. */
  1850. public function testQueryWithStackedFormatters()
  1851. {
  1852. $table = TableRegistry::get('authors');
  1853. $query = new Query($this->connection, $table);
  1854. $query->select()->formatResults(function ($results) {
  1855. $this->assertInstanceOf('Cake\ORM\ResultSet', $results);
  1856. return $results->indexBy('id');
  1857. });
  1858. $query->formatResults(function ($results) {
  1859. return $results->extract('name');
  1860. });
  1861. $expected = [
  1862. 1 => 'mariano',
  1863. 2 => 'nate',
  1864. 3 => 'larry',
  1865. 4 => 'garrett'
  1866. ];
  1867. $this->assertEquals($expected, $query->toArray());
  1868. }
  1869. /**
  1870. * Tests that getting results from a query having a contained association
  1871. * will not attach joins twice if count() is called on it afterwards
  1872. *
  1873. * @return void
  1874. */
  1875. public function testCountWithContainCallingAll()
  1876. {
  1877. $table = TableRegistry::get('articles');
  1878. $table->belongsTo('authors');
  1879. $query = $table->find()
  1880. ->select(['id', 'title'])
  1881. ->contain('authors')
  1882. ->limit(2);
  1883. $results = $query->all();
  1884. $this->assertCount(2, $results);
  1885. $this->assertEquals(3, $query->count());
  1886. }
  1887. /**
  1888. * Tests that it is possible to apply formatters inside the query builder
  1889. * for belongsTo associations
  1890. *
  1891. * @return void
  1892. */
  1893. public function testFormatBelongsToRecords()
  1894. {
  1895. $table = TableRegistry::get('articles');
  1896. $table->belongsTo('authors');
  1897. $query = $table->find()
  1898. ->contain(['authors' => function ($q) {
  1899. return $q
  1900. ->formatResults(function ($authors) {
  1901. return $authors->map(function ($author) {
  1902. $author->idCopy = $author->id;
  1903. return $author;
  1904. });
  1905. })
  1906. ->formatResults(function ($authors) {
  1907. return $authors->map(function ($author) {
  1908. $author->idCopy = $author->idCopy + 2;
  1909. return $author;
  1910. });
  1911. });
  1912. }]);
  1913. $query->formatResults(function ($results) {
  1914. return $results->combine('id', 'author.idCopy');
  1915. });
  1916. $results = $query->toArray();
  1917. $expected = [1 => 3, 2 => 5, 3 => 3];
  1918. $this->assertEquals($expected, $results);
  1919. }
  1920. /**
  1921. * Tests it is possible to apply formatters to deep relations.
  1922. *
  1923. * @return void
  1924. */
  1925. public function testFormatDeepAssocationRecords()
  1926. {
  1927. $table = TableRegistry::get('ArticlesTags');
  1928. $table->belongsTo('Articles');
  1929. $table->association('Articles')->target()->belongsTo('Authors');
  1930. $builder = function ($q) {
  1931. return $q
  1932. ->formatResults(function ($results) {
  1933. return $results->map(function ($result) {
  1934. $result->idCopy = $result->id;
  1935. return $result;
  1936. });
  1937. })
  1938. ->formatResults(function ($results) {
  1939. return $results->map(function ($result) {
  1940. $result->idCopy = $result->idCopy + 2;
  1941. return $result;
  1942. });
  1943. });
  1944. };
  1945. $query = $table->find()
  1946. ->contain(['Articles' => $builder, 'Articles.Authors' => $builder])
  1947. ->order(['Articles.id' => 'ASC']);
  1948. $query->formatResults(function ($results) {
  1949. return $results->map(function ($row) {
  1950. return sprintf(
  1951. '%s - %s - %s',
  1952. $row->tag_id,
  1953. $row->article->idCopy,
  1954. $row->article->author->idCopy
  1955. );
  1956. });
  1957. });
  1958. $expected = ['1 - 3 - 3', '2 - 3 - 3', '1 - 4 - 5', '3 - 4 - 5'];
  1959. $this->assertEquals($expected, $query->toArray());
  1960. }
  1961. /**
  1962. * Tests that formatters cna be applied to deep associations that are fetched using
  1963. * additional queries
  1964. *
  1965. * @return void
  1966. */
  1967. public function testFormatDeepDistantAssociationRecords()
  1968. {
  1969. $table = TableRegistry::get('authors');
  1970. $table->hasMany('articles');
  1971. $articles = $table->association('articles')->target();
  1972. $articles->hasMany('articlesTags');
  1973. $articles->association('articlesTags')->target()->belongsTo('tags');
  1974. $query = $table->find()->contain(['articles.articlesTags.tags' => function ($q) {
  1975. return $q->formatResults(function ($results) {
  1976. return $results->map(function ($tag) {
  1977. $tag->name .= ' - visited';
  1978. return $tag;
  1979. });
  1980. });
  1981. }]);
  1982. $query->mapReduce(function ($row, $key, $mr) {
  1983. foreach ((array)$row->articles as $article) {
  1984. foreach ((array)$article->articles_tags as $articleTag) {
  1985. $mr->emit($articleTag->tag->name);
  1986. }
  1987. }
  1988. });
  1989. $expected = ['tag1 - visited', 'tag2 - visited', 'tag1 - visited', 'tag3 - visited'];
  1990. $this->assertEquals($expected, $query->toArray());
  1991. }
  1992. /**
  1993. * Tests that custom finders are applied to associations when using the proxies
  1994. *
  1995. * @return void
  1996. */
  1997. public function testCustomFinderInBelongsTo()
  1998. {
  1999. $table = TableRegistry::get('ArticlesTags');
  2000. $table->belongsTo('Articles', [
  2001. 'className' => 'TestApp\Model\Table\ArticlesTable',
  2002. 'finder' => 'published'
  2003. ]);
  2004. $result = $table->find()->contain('Articles');
  2005. $this->assertCount(4, $result->extract('article')->filter()->toArray());
  2006. $table->Articles->updateAll(['published' => 'N'], ['1 = 1']);
  2007. $result = $table->find()->contain('Articles');
  2008. $this->assertCount(0, $result->extract('article')->filter()->toArray());
  2009. }
  2010. /**
  2011. * Test finding fields on the non-default table that
  2012. * have the same name as the primary table.
  2013. *
  2014. * @return void
  2015. */
  2016. public function testContainSelectedFields()
  2017. {
  2018. $table = TableRegistry::get('Articles');
  2019. $table->belongsTo('Authors');
  2020. $query = $table->find()
  2021. ->contain(['Authors'])
  2022. ->order(['Authors.id' => 'asc'])
  2023. ->select(['Authors.id']);
  2024. $results = $query->extract('Authors.id')->toList();
  2025. $expected = [1, 1, 3];
  2026. $this->assertEquals($expected, $results);
  2027. }
  2028. /**
  2029. * Tests that it is possible to attach more association when using a query
  2030. * builder for other associations
  2031. *
  2032. * @return void
  2033. */
  2034. public function testContainInAssociationQuery()
  2035. {
  2036. $table = TableRegistry::get('ArticlesTags');
  2037. $table->belongsTo('Articles');
  2038. $table->association('Articles')->target()->belongsTo('Authors');
  2039. $query = $table->find()
  2040. ->order(['Articles.id' => 'ASC'])
  2041. ->contain(['Articles' => function ($q) {
  2042. return $q->contain('Authors');
  2043. }]);
  2044. $results = $query->extract('article.author.name')->toArray();
  2045. $expected = ['mariano', 'mariano', 'larry', 'larry'];
  2046. $this->assertEquals($expected, $results);
  2047. }
  2048. /**
  2049. * Tests that it is possible to apply more `matching` conditions inside query
  2050. * builders for associations
  2051. *
  2052. * @return void
  2053. */
  2054. public function testContainInAssociationMatching()
  2055. {
  2056. $table = TableRegistry::get('authors');
  2057. $table->hasMany('articles');
  2058. $articles = $table->association('articles')->target();
  2059. $articles->hasMany('articlesTags');
  2060. $articles->association('articlesTags')->target()->belongsTo('tags');
  2061. $query = $table->find()->matching('articles.articlesTags', function ($q) {
  2062. return $q->matching('tags', function ($q) {
  2063. return $q->where(['tags.name' => 'tag3']);
  2064. });
  2065. });
  2066. $results = $query->toArray();
  2067. $this->assertCount(1, $results);
  2068. $this->assertEquals('tag3', $results[0]->_matchingData['tags']->name);
  2069. }
  2070. /**
  2071. * Tests __debugInfo
  2072. *
  2073. * @return void
  2074. */
  2075. public function testDebugInfo()
  2076. {
  2077. $table = TableRegistry::get('authors');
  2078. $table->hasMany('articles');
  2079. $query = $table->find()
  2080. ->where(['id > ' => 1])
  2081. ->bufferResults(false)
  2082. ->hydrate(false)
  2083. ->matching('articles')
  2084. ->applyOptions(['foo' => 'bar'])
  2085. ->formatResults(function ($results) {
  2086. return $results;
  2087. })
  2088. ->mapReduce(function ($item, $key, $mr) {
  2089. $mr->emit($item);
  2090. });
  2091. $expected = [
  2092. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  2093. 'sql' => $query->sql(),
  2094. 'params' => $query->valueBinder()->bindings(),
  2095. 'defaultTypes' => [
  2096. 'authors.id' => 'integer',
  2097. 'id' => 'integer',
  2098. 'authors.name' => 'string',
  2099. 'name' => 'string'
  2100. ],
  2101. 'decorators' => 0,
  2102. 'executed' => false,
  2103. 'hydrate' => false,
  2104. 'buffered' => false,
  2105. 'formatters' => 1,
  2106. 'mapReducers' => 1,
  2107. 'contain' => [],
  2108. 'matching' => [
  2109. 'articles' => [
  2110. 'queryBuilder' => null,
  2111. 'matching' => true,
  2112. 'joinType' => 'INNER'
  2113. ]
  2114. ],
  2115. 'extraOptions' => ['foo' => 'bar'],
  2116. 'repository' => $table
  2117. ];
  2118. $this->assertSame($expected, $query->__debugInfo());
  2119. }
  2120. /**
  2121. * Tests that the eagerLoaded function works and is transmitted correctly to eagerly
  2122. * loaded associations
  2123. *
  2124. * @return void
  2125. */
  2126. public function testEagerLoaded()
  2127. {
  2128. $table = TableRegistry::get('authors');
  2129. $table->hasMany('articles');
  2130. $query = $table->find()->contain(['articles' => function ($q) {
  2131. $this->assertTrue($q->eagerLoaded());
  2132. return $q;
  2133. }]);
  2134. $this->assertFalse($query->eagerLoaded());
  2135. $table->eventManager()->attach(function ($e, $q, $o, $primary) {
  2136. $this->assertTrue($primary);
  2137. }, 'Model.beforeFind');
  2138. TableRegistry::get('articles')
  2139. ->eventManager()->attach(function ($e, $q, $o, $primary) {
  2140. $this->assertFalse($primary);
  2141. }, 'Model.beforeFind');
  2142. $query->all();
  2143. }
  2144. /**
  2145. * Tests that columns from manual joins are also contained in the result set
  2146. *
  2147. * @return void
  2148. */
  2149. public function testColumnsFromJoin()
  2150. {
  2151. $table = TableRegistry::get('articles');
  2152. $results = $table->find()
  2153. ->select(['title', 'person.name'])
  2154. ->join([
  2155. 'person' => [
  2156. 'table' => 'authors',
  2157. 'conditions' => ['person.id = articles.author_id']
  2158. ]
  2159. ])
  2160. ->order(['articles.id' => 'ASC'])
  2161. ->hydrate(false)
  2162. ->toArray();
  2163. $expected = [
  2164. ['title' => 'First Article', 'person' => ['name' => 'mariano']],
  2165. ['title' => 'Second Article', 'person' => ['name' => 'larry']],
  2166. ['title' => 'Third Article', 'person' => ['name' => 'mariano']],
  2167. ];
  2168. $this->assertSame($expected, $results);
  2169. }
  2170. /**
  2171. * Tests that it is possible to use the same association aliases in the association
  2172. * chain for contain
  2173. *
  2174. * @dataProvider strategiesProviderBelongsTo
  2175. * @return void
  2176. */
  2177. public function testRepeatedAssociationAliases($strategy)
  2178. {
  2179. $table = TableRegistry::get('ArticlesTags');
  2180. $table->belongsTo('Articles', ['strategy' => $strategy]);
  2181. $table->belongsTo('Tags', ['strategy' => $strategy]);
  2182. TableRegistry::get('Tags')->belongsToMany('Articles');
  2183. $results = $table
  2184. ->find()
  2185. ->contain(['Articles', 'Tags.Articles'])
  2186. ->hydrate(false)
  2187. ->toArray();
  2188. $this->assertNotEmpty($results[0]['tag']['articles']);
  2189. $this->assertNotEmpty($results[0]['article']);
  2190. $this->assertNotEmpty($results[1]['tag']['articles']);
  2191. $this->assertNotEmpty($results[1]['article']);
  2192. $this->assertNotEmpty($results[2]['tag']['articles']);
  2193. $this->assertNotEmpty($results[2]['article']);
  2194. }
  2195. /**
  2196. * Tests that a hasOne association using the select strategy will still have the
  2197. * key present in the results when no match is found
  2198. *
  2199. * @return void
  2200. */
  2201. public function testAssociationKeyPresent()
  2202. {
  2203. $table = TableRegistry::get('Articles');
  2204. $table->hasOne('ArticlesTags', ['strategy' => 'select']);
  2205. $article = $table->find()->where(['id' => 3])
  2206. ->hydrate(false)
  2207. ->contain('ArticlesTags')
  2208. ->first();
  2209. $this->assertNull($article['articles_tag']);
  2210. }
  2211. /**
  2212. * Tests that queries can be serialized to JSON to get the results
  2213. *
  2214. * @return void
  2215. */
  2216. public function testJsonSerialize()
  2217. {
  2218. $table = TableRegistry::get('Articles');
  2219. $this->assertEquals(
  2220. json_encode($table->find()),
  2221. json_encode($table->find()->toArray())
  2222. );
  2223. }
  2224. /**
  2225. * Test that addFields() works in the basic case.
  2226. *
  2227. * @return void
  2228. */
  2229. public function testAutoFields()
  2230. {
  2231. $table = TableRegistry::get('Articles');
  2232. $result = $table->find('all')
  2233. ->select(['myField' => '(SELECT 20)'])
  2234. ->autoFields(true)
  2235. ->hydrate(false)
  2236. ->first();
  2237. $this->assertArrayHasKey('myField', $result);
  2238. $this->assertArrayHasKey('id', $result);
  2239. $this->assertArrayHasKey('title', $result);
  2240. }
  2241. /**
  2242. * Test autoFields with auto fields.
  2243. *
  2244. * @return void
  2245. */
  2246. public function testAutoFieldsWithAssociations()
  2247. {
  2248. $table = TableRegistry::get('Articles');
  2249. $table->belongsTo('Authors');
  2250. $result = $table->find()
  2251. ->select(['myField' => '(SELECT 2 + 2)'])
  2252. ->autoFields(true)
  2253. ->hydrate(false)
  2254. ->contain('Authors')
  2255. ->first();
  2256. $this->assertArrayHasKey('myField', $result);
  2257. $this->assertArrayHasKey('title', $result);
  2258. $this->assertArrayHasKey('author', $result);
  2259. $this->assertNotNull($result['author']);
  2260. $this->assertArrayHasKey('name', $result['author']);
  2261. }
  2262. /**
  2263. * Test autoFields in contain query builder
  2264. *
  2265. * @return void
  2266. */
  2267. public function testAutoFieldsWithContainQueryBuilder()
  2268. {
  2269. $table = TableRegistry::get('Articles');
  2270. $table->belongsTo('Authors');
  2271. $result = $table->find()
  2272. ->select(['myField' => '(SELECT 2 + 2)'])
  2273. ->autoFields(true)
  2274. ->hydrate(false)
  2275. ->contain(['Authors' => function ($q) {
  2276. return $q->select(['compute' => '(SELECT 2 + 20)'])
  2277. ->autoFields(true);
  2278. }])
  2279. ->first();
  2280. $this->assertArrayHasKey('myField', $result);
  2281. $this->assertArrayHasKey('title', $result);
  2282. $this->assertArrayHasKey('author', $result);
  2283. $this->assertNotNull($result['author']);
  2284. $this->assertArrayHasKey('name', $result['author']);
  2285. $this->assertArrayHasKey('compute', $result);
  2286. }
  2287. /**
  2288. * Test that autofields works with count()
  2289. *
  2290. * @return void
  2291. */
  2292. public function testAutoFieldsCount()
  2293. {
  2294. $table = TableRegistry::get('Articles');
  2295. $result = $table->find()
  2296. ->select(['myField' => '(SELECT (2 + 2))'])
  2297. ->autoFields(true)
  2298. ->count();
  2299. $this->assertEquals(3, $result);
  2300. }
  2301. /**
  2302. * test that cleanCopy makes a cleaned up clone.
  2303. *
  2304. * @return void
  2305. */
  2306. public function testCleanCopy()
  2307. {
  2308. $table = TableRegistry::get('Articles');
  2309. $table->hasMany('Comments');
  2310. $query = $table->find();
  2311. $query->offset(10)
  2312. ->limit(1)
  2313. ->order(['Articles.id' => 'DESC'])
  2314. ->contain(['Comments']);
  2315. $copy = $query->cleanCopy();
  2316. $this->assertNotSame($copy, $query);
  2317. $this->assertNotSame($copy->eagerLoader(), $query->eagerLoader());
  2318. $this->assertNotEmpty($copy->eagerLoader()->contain());
  2319. $this->assertNull($copy->clause('offset'));
  2320. $this->assertNull($copy->clause('limit'));
  2321. $this->assertNull($copy->clause('order'));
  2322. }
  2323. /**
  2324. * test that cleanCopy retains bindings
  2325. *
  2326. * @return void
  2327. */
  2328. public function testCleanCopyRetainsBindings()
  2329. {
  2330. $table = TableRegistry::get('Articles');
  2331. $query = $table->find();
  2332. $query->offset(10)
  2333. ->limit(1)
  2334. ->where(['Articles.id BETWEEN :start AND :end'])
  2335. ->order(['Articles.id' => 'DESC'])
  2336. ->bind(':start', 1)
  2337. ->bind(':end', 2);
  2338. $copy = $query->cleanCopy();
  2339. $this->assertNotEmpty($copy->valueBinder()->bindings());
  2340. }
  2341. /**
  2342. * test that cleanCopy makes a cleaned up clone with a beforeFind.
  2343. *
  2344. * @return void
  2345. */
  2346. public function testCleanCopyBeforeFind()
  2347. {
  2348. $table = TableRegistry::get('Articles');
  2349. $table->hasMany('Comments');
  2350. $table->eventManager()
  2351. ->attach(function ($event, $query) {
  2352. $query
  2353. ->limit(5)
  2354. ->order(['Articles.title' => 'DESC']);
  2355. }, 'Model.beforeFind');
  2356. $query = $table->find();
  2357. $query->offset(10)
  2358. ->limit(1)
  2359. ->order(['Articles.id' => 'DESC'])
  2360. ->contain(['Comments']);
  2361. $copy = $query->cleanCopy();
  2362. $this->assertNotSame($copy, $query);
  2363. $this->assertNull($copy->clause('offset'));
  2364. $this->assertNull($copy->clause('limit'));
  2365. $this->assertNull($copy->clause('order'));
  2366. }
  2367. /**
  2368. * Test that finder options sent through via contain are sent to custom finder.
  2369. *
  2370. * @return void
  2371. */
  2372. public function testContainFinderCanSpecifyOptions()
  2373. {
  2374. $table = TableRegistry::get('Articles');
  2375. $table->belongsTo(
  2376. 'Authors',
  2377. ['className' => 'TestApp\Model\Table\AuthorsTable']
  2378. );
  2379. $authorId = 1;
  2380. $resultWithoutAuthor = $table->find('all')
  2381. ->where(['Articles.author_id' => $authorId])
  2382. ->contain([
  2383. 'Authors' => [
  2384. 'finder' => ['byAuthor' => ['author_id' => 2]]
  2385. ]
  2386. ]);
  2387. $resultWithAuthor = $table->find('all')
  2388. ->where(['Articles.author_id' => $authorId])
  2389. ->contain([
  2390. 'Authors' => [
  2391. 'finder' => ['byAuthor' => ['author_id' => $authorId]]
  2392. ]
  2393. ]);
  2394. $this->assertEmpty($resultWithoutAuthor->first()['author']);
  2395. $this->assertEquals($authorId, $resultWithAuthor->first()['author']['id']);
  2396. }
  2397. /**
  2398. * Tests that it is possible to bind arguments to a query and it will return the right
  2399. * results
  2400. *
  2401. * @return void
  2402. */
  2403. public function testCustomBindings()
  2404. {
  2405. $table = TableRegistry::get('Articles');
  2406. $query = $table->find()->where(['id >' => 1]);
  2407. $query->where(function ($exp) {
  2408. return $exp->add('author_id = :author');
  2409. });
  2410. $query->bind(':author', 1, 'integer');
  2411. $this->assertEquals(1, $query->count());
  2412. $this->assertEquals(3, $query->first()->id);
  2413. }
  2414. /**
  2415. * Tests that it is possible to pass a custom join type for an association when
  2416. * using contain
  2417. *
  2418. * @return void
  2419. */
  2420. public function testContainWithCustomJoinType()
  2421. {
  2422. $table = TableRegistry::get('Articles');
  2423. $table->belongsTo('Authors');
  2424. $articles = $table->find()
  2425. ->contain([
  2426. 'Authors' => [
  2427. 'joinType' => 'inner',
  2428. 'conditions' => ['Authors.id' => 3]
  2429. ]
  2430. ])
  2431. ->toArray();
  2432. $this->assertCount(1, $articles);
  2433. $this->assertEquals(3, $articles[0]->author->id);
  2434. }
  2435. /**
  2436. * Tests that it is possible to override the contain strategy using the
  2437. * containments array. In this case, no inner join will be made and for that
  2438. * reason, the parent association will not be filtered as the strategy changed
  2439. * from join to select.
  2440. *
  2441. * @return void
  2442. */
  2443. public function testContainWithStrategyOverride()
  2444. {
  2445. $table = TableRegistry::get('Articles');
  2446. $table->belongsTo('Authors', [
  2447. 'joinType' => 'INNER'
  2448. ]);
  2449. $articles = $table->find()
  2450. ->contain([
  2451. 'Authors' => [
  2452. 'strategy' => 'select',
  2453. 'conditions' => ['Authors.id' => 3]
  2454. ]
  2455. ])
  2456. ->toArray();
  2457. $this->assertCount(3, $articles);
  2458. $this->assertEquals(3, $articles[1]->author->id);
  2459. $this->assertNull($articles[0]->author);
  2460. $this->assertNull($articles[2]->author);
  2461. }
  2462. /**
  2463. * Tests that it is possible to call matching and contain on the same
  2464. * association.
  2465. *
  2466. * @return void
  2467. */
  2468. public function testMatchingWithContain()
  2469. {
  2470. $query = new Query($this->connection, $this->table);
  2471. $table = TableRegistry::get('authors');
  2472. $table->hasMany('articles');
  2473. TableRegistry::get('articles')->belongsToMany('tags');
  2474. $result = $query->repository($table)
  2475. ->select()
  2476. ->matching('articles.tags', function ($q) {
  2477. return $q->where(['tags.id' => 2]);
  2478. })
  2479. ->contain('articles')
  2480. ->first();
  2481. $this->assertEquals(1, $result->id);
  2482. $this->assertCount(2, $result->articles);
  2483. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2484. }
  2485. /**
  2486. * Tests that it is possible to call matching and contain on the same
  2487. * association with only one level of depth.
  2488. *
  2489. * @return void
  2490. */
  2491. public function testNotSoFarMatchingWithContainOnTheSameAssociation()
  2492. {
  2493. $table = TableRegistry::get('articles');
  2494. $table->belongsToMany('tags');
  2495. $result = $table->find()
  2496. ->matching('tags', function ($q) {
  2497. return $q->where(['tags.id' => 2]);
  2498. })
  2499. ->contain('tags')
  2500. ->first();
  2501. $this->assertEquals(1, $result->id);
  2502. $this->assertCount(2, $result->tags);
  2503. $this->assertEquals(2, $result->_matchingData['tags']->id);
  2504. }
  2505. /**
  2506. * Tests that select() can be called with Table and Association
  2507. * instance
  2508. *
  2509. * @return void
  2510. */
  2511. public function testSelectWithTableAndAssociationInstance()
  2512. {
  2513. $table = TableRegistry::get('articles');
  2514. $table->belongsTo('authors');
  2515. $result = $table
  2516. ->find()
  2517. ->select(function ($q) {
  2518. return ['foo' => $q->newExpr('1 + 1')];
  2519. })
  2520. ->select($table)
  2521. ->select($table->authors)
  2522. ->contain(['authors'])
  2523. ->first();
  2524. $expected = $table
  2525. ->find()
  2526. ->select(function ($q) {
  2527. return ['foo' => $q->newExpr('1 + 1')];
  2528. })
  2529. ->autoFields(true)
  2530. ->contain(['authors'])
  2531. ->first();
  2532. $this->assertNotEmpty($result);
  2533. $this->assertEquals($expected, $result);
  2534. }
  2535. /**
  2536. * Tests that isEmpty() can be called on a query
  2537. *
  2538. * @return void
  2539. */
  2540. public function testIsEmpty()
  2541. {
  2542. $table = TableRegistry::get('articles');
  2543. $this->assertFalse($table->find()->isEmpty());
  2544. $this->assertTrue($table->find()->where(['id' => -1])->isEmpty());
  2545. }
  2546. /**
  2547. * Tests that leftJoinWith() creates a left join with a given association and
  2548. * that no fields from such association are loaded.
  2549. *
  2550. * @return void
  2551. */
  2552. public function testLeftJoinWith()
  2553. {
  2554. $table = TableRegistry::get('authors');
  2555. $table->hasMany('articles');
  2556. $table->articles->deleteAll(['author_id' => 4]);
  2557. $results = $table
  2558. ->find()
  2559. ->select(['total_articles' => 'count(articles.id)'])
  2560. ->autoFields(true)
  2561. ->leftJoinWith('articles')
  2562. ->group(['authors.id', 'authors.name']);
  2563. $expected = [
  2564. 1 => 2,
  2565. 2 => 0,
  2566. 3 => 1,
  2567. 4 => 0
  2568. ];
  2569. $this->assertEquals($expected, $results->combine('id', 'total_articles')->toArray());
  2570. $fields = ['total_articles', 'id', 'name'];
  2571. $this->assertEquals($fields, array_keys($results->first()->toArray()));
  2572. $results = $table
  2573. ->find()
  2574. ->leftJoinWith('articles')
  2575. ->where(['articles.id IS' => null]);
  2576. $this->assertEquals([2, 4], $results->extract('id')->toList());
  2577. $this->assertEquals(['id', 'name'], array_keys($results->first()->toArray()));
  2578. $results = $table
  2579. ->find()
  2580. ->leftJoinWith('articles')
  2581. ->where(['articles.id IS NOT' => null])
  2582. ->order(['authors.id']);
  2583. $this->assertEquals([1, 1, 3], $results->extract('id')->toList());
  2584. $this->assertEquals(['id', 'name'], array_keys($results->first()->toArray()));
  2585. }
  2586. /**
  2587. * Tests that leftJoinWith() creates a left join with a given association and
  2588. * that no fields from such association are loaded.
  2589. *
  2590. * @return void
  2591. */
  2592. public function testLeftJoinWithNested()
  2593. {
  2594. $table = TableRegistry::get('authors');
  2595. $articles = $table->hasMany('articles');
  2596. $articles->belongsToMany('tags');
  2597. $results = $table
  2598. ->find()
  2599. ->select(['total_articles' => 'count(articles.id)'])
  2600. ->leftJoinWith('articles.tags', function ($q) {
  2601. return $q->where(['tags.name' => 'tag3']);
  2602. })
  2603. ->autoFields(true)
  2604. ->group(['authors.id', 'authors.name']);
  2605. $expected = [
  2606. 1 => 2,
  2607. 2 => 0,
  2608. 3 => 1,
  2609. 4 => 0
  2610. ];
  2611. $this->assertEquals($expected, $results->combine('id', 'total_articles')->toArray());
  2612. $fields = ['total_articles', 'id', 'name'];
  2613. $this->assertEquals($fields, array_keys($results->first()->toArray()));
  2614. }
  2615. /**
  2616. * Tests that leftJoinWith() can be used with select()
  2617. *
  2618. * @return void
  2619. */
  2620. public function testLeftJoinWithSelect()
  2621. {
  2622. $table = TableRegistry::get('authors');
  2623. $articles = $table->hasMany('articles');
  2624. $articles->belongsToMany('tags');
  2625. $results = $table
  2626. ->find()
  2627. ->leftJoinWith('articles.tags', function ($q) {
  2628. return $q
  2629. ->select(['articles.id', 'articles.title', 'tags.name'])
  2630. ->where(['tags.name' => 'tag3']);
  2631. })
  2632. ->autoFields(true)
  2633. ->where(['ArticlesTags.tag_id' => 3])
  2634. ->distinct(['authors.id'])
  2635. ->all();
  2636. $expected = ['id' => 2, 'title' => 'Second Article'];
  2637. $this->assertEquals(
  2638. $expected,
  2639. $results->first()->_matchingData['articles']->toArray()
  2640. );
  2641. $this->assertEquals(
  2642. ['name' => 'tag3'],
  2643. $results->first()->_matchingData['tags']->toArray()
  2644. );
  2645. }
  2646. /**
  2647. * Tests innerJoinWith()
  2648. *
  2649. * @return void
  2650. */
  2651. public function testInnerJoinWith()
  2652. {
  2653. $table = TableRegistry::get('authors');
  2654. $table->hasMany('articles');
  2655. $results = $table
  2656. ->find()
  2657. ->innerJoinWith('articles', function ($q) {
  2658. return $q->where(['articles.title' => 'Third Article']);
  2659. });
  2660. $expected = [
  2661. [
  2662. 'id' => 1,
  2663. 'name' => 'mariano'
  2664. ]
  2665. ];
  2666. $this->assertEquals($expected, $results->hydrate(false)->toArray());
  2667. }
  2668. /**
  2669. * Tests innerJoinWith() with nested associations
  2670. *
  2671. * @return void
  2672. */
  2673. public function testInnerJoinWithNested()
  2674. {
  2675. $table = TableRegistry::get('authors');
  2676. $articles = $table->hasMany('articles');
  2677. $articles->belongsToMany('tags');
  2678. $results = $table
  2679. ->find()
  2680. ->innerJoinWith('articles.tags', function ($q) {
  2681. return $q->where(['tags.name' => 'tag3']);
  2682. });
  2683. $expected = [
  2684. [
  2685. 'id' => 3,
  2686. 'name' => 'larry'
  2687. ]
  2688. ];
  2689. $this->assertEquals($expected, $results->hydrate(false)->toArray());
  2690. }
  2691. /**
  2692. * Tests innerJoinWith() with select
  2693. *
  2694. * @return void
  2695. */
  2696. public function testInnerJoinWithSelect()
  2697. {
  2698. $table = TableRegistry::get('authors');
  2699. $table->hasMany('articles');
  2700. $results = $table
  2701. ->find()
  2702. ->autoFields(true)
  2703. ->innerJoinWith('articles', function ($q) {
  2704. return $q->select(['id', 'author_id', 'title', 'body', 'published']);
  2705. })
  2706. ->toArray();
  2707. $expected = $table
  2708. ->find()
  2709. ->matching('articles')
  2710. ->toArray();
  2711. $this->assertEquals($expected, $results);
  2712. }
  2713. /**
  2714. * Tests notMatching() with and without conditions
  2715. *
  2716. * @return void
  2717. */
  2718. public function testNotMatching()
  2719. {
  2720. $table = TableRegistry::get('authors');
  2721. $table->hasMany('articles');
  2722. $results = $table->find()
  2723. ->hydrate(false)
  2724. ->notMatching('articles')
  2725. ->toArray();
  2726. $expected = [
  2727. ['id' => 2, 'name' => 'nate'],
  2728. ['id' => 4, 'name' => 'garrett'],
  2729. ];
  2730. $this->assertEquals($expected, $results);
  2731. $results = $table->find()
  2732. ->hydrate(false)
  2733. ->notMatching('articles', function ($q) {
  2734. return $q->where(['articles.author_id' => 1]);
  2735. })
  2736. ->toArray();
  2737. $expected = [
  2738. ['id' => 2, 'name' => 'nate'],
  2739. ['id' => 3, 'name' => 'larry'],
  2740. ['id' => 4, 'name' => 'garrett'],
  2741. ];
  2742. $this->assertEquals($expected, $results);
  2743. }
  2744. /**
  2745. * Tests notMatching() with a belongsToMany association
  2746. *
  2747. * @return void
  2748. */
  2749. public function testNotMatchingBelongsToMany()
  2750. {
  2751. $table = TableRegistry::get('articles');
  2752. $table->belongsToMany('tags');
  2753. $results = $table->find()
  2754. ->hydrate(false)
  2755. ->notMatching('tags', function ($q) {
  2756. return $q->where(['tags.name' => 'tag2']);
  2757. })
  2758. ->toArray();
  2759. $expected = [
  2760. [
  2761. 'id' => 2,
  2762. 'author_id' => 3,
  2763. 'title' => 'Second Article',
  2764. 'body' => 'Second Article Body',
  2765. 'published' => 'Y'
  2766. ],
  2767. [
  2768. 'id' => 3,
  2769. 'author_id' => 1,
  2770. 'title' => 'Third Article',
  2771. 'body' => 'Third Article Body',
  2772. 'published' => 'Y'
  2773. ]
  2774. ];
  2775. $this->assertEquals($expected, $results);
  2776. }
  2777. /**
  2778. * Tests notMatching() with a deeply nested belongsToMany association.
  2779. *
  2780. * @return void
  2781. */
  2782. public function testNotMatchingDeep()
  2783. {
  2784. $table = TableRegistry::get('authors');
  2785. $articles = $table->hasMany('articles');
  2786. $articles->belongsToMany('tags');
  2787. $results = $table->find()
  2788. ->hydrate(false)
  2789. ->notMatching('articles.tags', function ($q) {
  2790. return $q->where(['tags.name' => 'tag3']);
  2791. })
  2792. ->distinct(['authors.id']);
  2793. $this->assertEquals([1, 2, 4], $results->extract('id')->toList());
  2794. $results = $table->find()
  2795. ->hydrate(false)
  2796. ->notMatching('articles.tags', function ($q) {
  2797. return $q->where(['tags.name' => 'tag3']);
  2798. })
  2799. ->matching('articles')
  2800. ->distinct(['authors.id']);
  2801. $this->assertEquals([1], $results->extract('id')->toList());
  2802. }
  2803. /**
  2804. * Tests that it is possible to nest a notMatching call inside another
  2805. * eagerloader function.
  2806. *
  2807. * @return void
  2808. */
  2809. public function testNotMatchingNested()
  2810. {
  2811. $table = TableRegistry::get('authors');
  2812. $articles = $table->hasMany('articles');
  2813. $articles->belongsToMany('tags');
  2814. $results = $table->find()
  2815. ->hydrate(false)
  2816. ->matching('articles', function ($q) {
  2817. return $q->notMatching('tags', function ($q) {
  2818. return $q->where(['tags.name' => 'tag3']);
  2819. });
  2820. })
  2821. ->order(['authors.id' => 'ASC', 'articles.id' => 'ASC']);
  2822. $expected = [
  2823. 'id' => 1,
  2824. 'name' => 'mariano',
  2825. '_matchingData' => [
  2826. 'articles' => [
  2827. 'id' => 1,
  2828. 'author_id' => 1,
  2829. 'title' => 'First Article',
  2830. 'body' => 'First Article Body',
  2831. 'published' => 'Y'
  2832. ]
  2833. ]
  2834. ];
  2835. $this->assertEquals($expected, $results->first());
  2836. }
  2837. }