ModelCriteria.php 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841
  1. <?php
  2. /**
  3. * This file is part of the Propel package.
  4. * For the full copyright and license information, please view the LICENSE
  5. * file that was distributed with this source code.
  6. *
  7. * @license MIT License
  8. */
  9. /**
  10. * This class extends the Criteria by adding runtime introspection abilities
  11. * in order to ease the building of queries.
  12. *
  13. * A ModelCriteria requires additional information to be initialized.
  14. * Using a model name and tablemaps, a ModelCriteria can do more powerful things than a simple Criteria
  15. *
  16. * magic methods:
  17. *
  18. * @method ModelCriteria leftJoin($relation) Adds a LEFT JOIN clause to the query
  19. * @method ModelCriteria rightJoin($relation) Adds a RIGHT JOIN clause to the query
  20. * @method ModelCriteria innerJoin($relation) Adds a INNER JOIN clause to the query
  21. *
  22. * @author François Zaninotto
  23. * @version $Revision: 1799 $
  24. * @package propel.runtime.query
  25. */
  26. class ModelCriteria extends Criteria
  27. {
  28. const MODEL_CLAUSE = "MODEL CLAUSE";
  29. const MODEL_CLAUSE_ARRAY = "MODEL CLAUSE ARRAY";
  30. const MODEL_CLAUSE_LIKE = "MODEL CLAUSE LIKE";
  31. const MODEL_CLAUSE_SEVERAL = "MODEL CLAUSE SEVERAL";
  32. const FORMAT_STATEMENT = 'PropelStatementFormatter';
  33. const FORMAT_ARRAY = 'PropelArrayFormatter';
  34. const FORMAT_OBJECT = 'PropelObjectFormatter';
  35. const FORMAT_ON_DEMAND = 'PropelOnDemandFormatter';
  36. protected $modelName;
  37. protected $modelPeerName;
  38. protected $modelAlias;
  39. protected $useAliasInSQL = false;
  40. protected $tableMap;
  41. protected $primaryCriteria;
  42. protected $formatter;
  43. protected $defaultFormatterClass = ModelCriteria::FORMAT_OBJECT;
  44. protected $with = array();
  45. protected $isWithOneToMany = false;
  46. protected $previousJoin = null; // this is introduced to prevent useQuery->join from going wrong
  47. protected $isKeepQuery = false; // whether to clone the current object before termination methods
  48. /**
  49. * Creates a new instance with the default capacity which corresponds to
  50. * the specified database.
  51. *
  52. * @param string $dbName The dabase name
  53. * @param string $modelName The phpName of a model, e.g. 'Book'
  54. * @param string $modelAlias The alias for the model in this query, e.g. 'b'
  55. */
  56. public function __construct($dbName = null, $modelName, $modelAlias = null)
  57. {
  58. $this->setDbName($dbName);
  59. $this->originalDbName = $dbName;
  60. $this->modelName = $modelName;
  61. $this->modelPeerName = constant($this->modelName . '::PEER');
  62. $this->modelAlias = $modelAlias;
  63. $this->tableMap = Propel::getDatabaseMap($this->getDbName())->getTableByPhpName($this->modelName);
  64. }
  65. /**
  66. * Returns the name of the class for this model criteria
  67. *
  68. * @return string
  69. */
  70. public function getModelName()
  71. {
  72. return $this->modelName;
  73. }
  74. /**
  75. * Sets the alias for the model in this query
  76. *
  77. * @param string $modelAlias The model alias
  78. * @param boolean $useAliasInSQL Whether to use the alias in the SQL code (false by default)
  79. *
  80. * @return ModelCriteria The current object, for fluid interface
  81. */
  82. public function setModelAlias($modelAlias, $useAliasInSQL = false)
  83. {
  84. if ($useAliasInSQL) {
  85. $this->addAlias($modelAlias, $this->tableMap->getName());
  86. $this->useAliasInSQL = true;
  87. }
  88. $this->modelAlias = $modelAlias;
  89. return $this;
  90. }
  91. /**
  92. * Returns the alias of the main class for this model criteria
  93. *
  94. * @return string The model alias
  95. */
  96. public function getModelAlias()
  97. {
  98. return $this->modelAlias;
  99. }
  100. /**
  101. * Return the string to use in a clause as a model prefix for the main model
  102. *
  103. * @return string The model alias if it exists, the model name if not
  104. */
  105. public function getModelAliasOrName()
  106. {
  107. return $this->modelAlias ? $this->modelAlias : $this->modelName;
  108. }
  109. /**
  110. * Returns the name of the Peer class for this model criteria
  111. *
  112. * @return string
  113. */
  114. public function getModelPeerName()
  115. {
  116. return $this->modelPeerName;
  117. }
  118. /**
  119. * Returns the TabkleMap object for this Criteria
  120. *
  121. * @return TableMap
  122. */
  123. public function getTableMap()
  124. {
  125. return $this->tableMap;
  126. }
  127. /**
  128. * Sets the formatter to use for the find() output
  129. * Formatters must extend PropelFormatter
  130. * Use the ModelCriteria constants for class names:
  131. * <code>
  132. * $c->setFormatter(ModelCriteria::FORMAT_ARRAY);
  133. * </code>
  134. *
  135. * @param string|PropelFormatter $formatter a formatter class name, or a formatter instance
  136. * @return ModelCriteria The current object, for fluid interface
  137. */
  138. public function setFormatter($formatter)
  139. {
  140. if(is_string($formatter)) {
  141. $formatter = new $formatter();
  142. }
  143. if (!$formatter instanceof PropelFormatter) {
  144. throw new PropelException('setFormatter() only accepts classes extending PropelFormatter');
  145. }
  146. $this->formatter = $formatter;
  147. return $this;
  148. }
  149. /**
  150. * Gets the formatter to use for the find() output
  151. * Defaults to an instance of ModelCriteria::$defaultFormatterClass, i.e. PropelObjectsFormatter
  152. *
  153. * @return PropelFormatter
  154. */
  155. public function getFormatter()
  156. {
  157. if (null === $this->formatter) {
  158. $formatterClass = $this->defaultFormatterClass;
  159. $this->formatter = new $formatterClass();
  160. }
  161. return $this->formatter;
  162. }
  163. /**
  164. * Adds a condition on a column based on a pseudo SQL clause
  165. * but keeps it for later use with combine()
  166. * Until combine() is called, the condition is not added to the query
  167. * Uses introspection to translate the column phpName into a fully qualified name
  168. * <code>
  169. * $c->condition('cond1', 'b.Title = ?', 'foo');
  170. * </code>
  171. *
  172. * @see Criteria::add()
  173. *
  174. * @param string $conditionName A name to store the condition for a later combination with combine()
  175. * @param string $clause The pseudo SQL clause, e.g. 'AuthorId = ?'
  176. * @param mixed $value A value for the condition
  177. *
  178. * @return ModelCriteria The current object, for fluid interface
  179. */
  180. public function condition($conditionName, $clause, $value = null)
  181. {
  182. $this->addCond($conditionName, $this->getCriterionForClause($clause, $value), null, null);
  183. return $this;
  184. }
  185. /**
  186. * Adds a condition on a column based on a column phpName and a value
  187. * Uses introspection to translate the column phpName into a fully qualified name
  188. * Warning: recognizes only the phpNames of the main Model (not joined tables)
  189. * <code>
  190. * $c->filterBy('Title', 'foo');
  191. * </code>
  192. *
  193. * @see Criteria::add()
  194. *
  195. * @param string $column A string representing thecolumn phpName, e.g. 'AuthorId'
  196. * @param mixed $value A value for the condition
  197. * @param string $comparison What to use for the column comparison, defaults to Criteria::EQUAL
  198. *
  199. * @return ModelCriteria The current object, for fluid interface
  200. */
  201. public function filterBy($column, $value, $comparison = Criteria::EQUAL)
  202. {
  203. return $this->add($this->getRealColumnName($column), $value, $comparison);
  204. }
  205. /**
  206. * Adds a list of conditions on the columns of the current model
  207. * Uses introspection to translate the column phpName into a fully qualified name
  208. * Warning: recognizes only the phpNames of the main Model (not joined tables)
  209. * <code>
  210. * $c->filterByArray(array(
  211. * 'Title' => 'War And Peace',
  212. * 'Publisher' => $publisher
  213. * ));
  214. * </code>
  215. *
  216. * @see filterBy()
  217. *
  218. * @param mixed $conditions An array of conditions, using column phpNames as key
  219. *
  220. * @return ModelCriteria The current object, for fluid interface
  221. */
  222. public function filterByArray($conditions)
  223. {
  224. foreach ($conditions as $column => $args) {
  225. call_user_func_array(array($this, 'filterBy' . $column), (array) $args);
  226. }
  227. return $this;
  228. }
  229. /**
  230. * Adds a condition on a column based on a pseudo SQL clause
  231. * Uses introspection to translate the column phpName into a fully qualified name
  232. * <code>
  233. * // simple clause
  234. * $c->where('b.Title = ?', 'foo');
  235. * // named conditions
  236. * $c->condition('cond1', 'b.Title = ?', 'foo');
  237. * $c->condition('cond2', 'b.ISBN = ?', 12345);
  238. * $c->where(array('cond1', 'cond2'), Criteria::LOGICAL_OR);
  239. * </code>
  240. *
  241. * @see Criteria::add()
  242. *
  243. * @param mixed $clause A string representing the pseudo SQL clause, e.g. 'Book.AuthorId = ?'
  244. * Or an array of condition names
  245. * @param mixed $value A value for the condition
  246. *
  247. * @return ModelCriteria The current object, for fluid interface
  248. */
  249. public function where($clause, $value = null)
  250. {
  251. if (is_array($clause)) {
  252. // where(array('cond1', 'cond2'), Criteria::LOGICAL_OR)
  253. $criterion = $this->getCriterionForConditions($clause, $value);
  254. } else {
  255. // where('Book.AuthorId = ?', 12)
  256. $criterion = $this->getCriterionForClause($clause, $value);
  257. }
  258. $this->addAnd($criterion, null, null);
  259. return $this;
  260. }
  261. /**
  262. * Adds a condition on a column based on a pseudo SQL clause
  263. * Uses introspection to translate the column phpName into a fully qualified name
  264. * <code>
  265. * // simple clause
  266. * $c->orWhere('b.Title = ?', 'foo');
  267. * // named conditions
  268. * $c->condition('cond1', 'b.Title = ?', 'foo');
  269. * $c->condition('cond2', 'b.ISBN = ?', 12345);
  270. * $c->orWhere(array('cond1', 'cond2'), Criteria::LOGICAL_OR);
  271. * </code>
  272. *
  273. * @see Criteria::addOr()
  274. *
  275. * @param string $clause The pseudo SQL clause, e.g. 'AuthorId = ?'
  276. * @param mixed $value A value for the condition
  277. *
  278. * @return ModelCriteria The current object, for fluid interface
  279. */
  280. public function orWhere($clause, $value = null)
  281. {
  282. if (is_array($clause)) {
  283. // orWhere(array('cond1', 'cond2'), Criteria::LOGICAL_OR)
  284. $criterion = $this->getCriterionForConditions($clause, $value);
  285. } else {
  286. // orWhere('Book.AuthorId = ?', 12)
  287. $criterion = $this->getCriterionForClause($clause, $value);
  288. }
  289. $this->addOr($criterion, null, null);
  290. return $this;
  291. }
  292. /**
  293. * Adds a having condition on a column based on a pseudo SQL clause
  294. * Uses introspection to translate the column phpName into a fully qualified name
  295. * <code>
  296. * // simple clause
  297. * $c->having('b.Title = ?', 'foo');
  298. * // named conditions
  299. * $c->condition('cond1', 'b.Title = ?', 'foo');
  300. * $c->condition('cond2', 'b.ISBN = ?', 12345);
  301. * $c->having(array('cond1', 'cond2'), Criteria::LOGICAL_OR);
  302. * </code>
  303. *
  304. * @see Criteria::addHaving()
  305. *
  306. * @param mixed $clause A string representing the pseudo SQL clause, e.g. 'Book.AuthorId = ?'
  307. * Or an array of condition names
  308. * @param mixed $value A value for the condition
  309. *
  310. * @return ModelCriteria The current object, for fluid interface
  311. */
  312. public function having($clause, $value = null)
  313. {
  314. if (is_array($clause)) {
  315. // having(array('cond1', 'cond2'), Criteria::LOGICAL_OR)
  316. $criterion = $this->getCriterionForConditions($clause, $value);
  317. } else {
  318. // having('Book.AuthorId = ?', 12)
  319. $criterion = $this->getCriterionForClause($clause, $value);
  320. }
  321. $this->addHaving($criterion);
  322. return $this;
  323. }
  324. /**
  325. * Adds an ORDER BY clause to the query
  326. * Usability layer on top of Criteria::addAscendingOrderByColumn() and Criteria::addDescendingOrderByColumn()
  327. * Infers $column and $order from $columnName and some optional arguments
  328. * Examples:
  329. * $c->orderBy('Book.CreatedAt')
  330. * => $c->addAscendingOrderByColumn(BookPeer::CREATED_AT)
  331. * $c->orderBy('Book.CategoryId', 'desc')
  332. * => $c->addDescendingOrderByColumn(BookPeer::CATEGORY_ID)
  333. *
  334. * @param string $columnName The column to order by
  335. * @param string $order The sorting order. Criteria::ASC by default, also accepts Criteria::DESC
  336. *
  337. * @return ModelCriteria The current object, for fluid interface
  338. */
  339. public function orderBy($columnName, $order = Criteria::ASC)
  340. {
  341. list($column, $realColumnName) = $this->getColumnFromName($columnName, false);
  342. $order = strtoupper($order);
  343. switch ($order) {
  344. case Criteria::ASC:
  345. $this->addAscendingOrderByColumn($realColumnName);
  346. break;
  347. case Criteria::DESC:
  348. $this->addDescendingOrderByColumn($realColumnName);
  349. break;
  350. default:
  351. throw new PropelException('ModelCriteria::orderBy() only accepts Criteria::ASC or Criteria::DESC as argument');
  352. }
  353. return $this;
  354. }
  355. /**
  356. * Adds a GROUB BY clause to the query
  357. * Usability layer on top of Criteria::addGroupByColumn()
  358. * Infers $column $columnName
  359. * Examples:
  360. * $c->groupBy('Book.AuthorId')
  361. * => $c->addGroupByColumn(BookPeer::AUTHOR_ID)
  362. *
  363. * @param string $columnName The column to group by
  364. *
  365. * @return ModelCriteria The current object, for fluid interface
  366. */
  367. public function groupBy($columnName)
  368. {
  369. list($column, $realColumnName) = $this->getColumnFromName($columnName, false);
  370. $this->addGroupByColumn($realColumnName);
  371. return $this;
  372. }
  373. /**
  374. * Adds a DISTINCT clause to the query
  375. * Alias for Criteria::setDistinct()
  376. *
  377. * @return ModelCriteria The current object, for fluid interface
  378. */
  379. public function distinct()
  380. {
  381. $this->setDistinct();
  382. return $this;
  383. }
  384. /**
  385. * Adds a LIMIT clause (or its subselect equivalent) to the query
  386. * Alias for Criteria:::setLimit()
  387. *
  388. * @param int $limit Maximum number of results to return by the query
  389. *
  390. * @return ModelCriteria The current object, for fluid interface
  391. */
  392. public function limit($limit)
  393. {
  394. $this->setLimit($limit);
  395. return $this;
  396. }
  397. /**
  398. * Adds an OFFSET clause (or its subselect equivalent) to the query
  399. * Alias for of Criteria::setOffset()
  400. *
  401. * @param int $offset Offset of the first result to return
  402. *
  403. * @return ModelCriteria The current object, for fluid interface
  404. */
  405. public function offset($offset)
  406. {
  407. $this->setOffset($offset);
  408. return $this;
  409. }
  410. /**
  411. * This method returns the previousJoin for this ModelCriteria,
  412. * by default this is null, but after useQuery this is set the to the join of that use
  413. *
  414. * @return Join the previousJoin for this ModelCriteria
  415. */
  416. public function getPreviousJoin()
  417. {
  418. return $this->previousJoin;
  419. }
  420. /**
  421. * This method sets the previousJoin for this ModelCriteria,
  422. * by default this is null, but after useQuery this is set the to the join of that use
  423. *
  424. * @param Join $previousJoin The previousJoin for this ModelCriteria
  425. */
  426. public function setPreviousJoin(Join $previousJoin)
  427. {
  428. $this->previousJoin = $previousJoin;
  429. }
  430. /**
  431. * This method returns an already defined join clause from the query
  432. *
  433. * @param string $name The name of the join clause
  434. *
  435. * @return Join A join object
  436. */
  437. public function getJoin($name)
  438. {
  439. return $this->joins[$name];
  440. }
  441. /**
  442. * Adds a JOIN clause to the query
  443. * Infers the ON clause from a relation name
  444. * Uses the Propel table maps, based on the schema, to guess the related columns
  445. * Beware that the default JOIN operator is INNER JOIN, while Criteria defaults to WHERE
  446. * Examples:
  447. * <code>
  448. * $c->join('Book.Author');
  449. * => $c->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::INNER_JOIN);
  450. * $c->join('Book.Author', Criteria::RIGHT_JOIN);
  451. * => $c->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::RIGHT_JOIN);
  452. * $c->join('Book.Author a', Criteria::RIGHT_JOIN);
  453. * => $c->addAlias('a', AuthorPeer::TABLE_NAME);
  454. * => $c->addJoin(BookPeer::AUTHOR_ID, 'a.ID', Criteria::RIGHT_JOIN);
  455. * </code>
  456. *
  457. * @param string $relation Relation to use for the join
  458. * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
  459. *
  460. * @return ModelCriteria The current object, for fluid interface
  461. */
  462. public function join($relation, $joinType = Criteria::INNER_JOIN)
  463. {
  464. // relation looks like '$leftName.$relationName $relationAlias'
  465. list($fullName, $relationAlias) = self::getClassAndAlias($relation);
  466. if (strpos($fullName, '.') === false) {
  467. // simple relation name, refers to the current table
  468. $leftName = $this->getModelAliasOrName();
  469. $relationName = $fullName;
  470. $previousJoin = $this->getPreviousJoin();
  471. $tableMap = $this->getTableMap();
  472. } else {
  473. list($leftName, $relationName) = explode('.', $fullName);
  474. // find the TableMap for the left table using the $leftName
  475. if ($leftName == $this->getModelAliasOrName()) {
  476. $previousJoin = $this->getPreviousJoin();
  477. $tableMap = $this->getTableMap();
  478. } elseif (isset($this->joins[$leftName])) {
  479. $previousJoin = $this->joins[$leftName];
  480. $tableMap = $previousJoin->getTableMap();
  481. } else {
  482. throw new PropelException('Unknown table or alias ' . $leftName);
  483. }
  484. }
  485. $leftTableAlias = isset($this->aliases[$leftName]) ? $leftName : null;
  486. // find the RelationMap in the TableMap using the $relationName
  487. if(!$tableMap->hasRelation($relationName)) {
  488. throw new PropelException('Unknown relation ' . $relationName . ' on the ' . $leftName .' table');
  489. }
  490. $relationMap = $tableMap->getRelation($relationName);
  491. // create a ModelJoin object for this join
  492. $join = new ModelJoin();
  493. $join->setJoinType($joinType);
  494. if(null !== $previousJoin) {
  495. $join->setPreviousJoin($previousJoin);
  496. }
  497. $join->setRelationMap($relationMap, $leftTableAlias, $relationAlias);
  498. // add the ModelJoin to the current object
  499. if($relationAlias !== null) {
  500. $this->addAlias($relationAlias, $relationMap->getRightTable()->getName());
  501. $this->addJoinObject($join, $relationAlias);
  502. } else {
  503. $this->addJoinObject($join, $relationName);
  504. }
  505. return $this;
  506. }
  507. /**
  508. * Add a join object to the Criteria
  509. * @see Criteria::addJoinObject()
  510. * @param Join $join A join object
  511. *
  512. * @return ModelCriteria The current object, for fluid interface
  513. */
  514. public function addJoinObject(Join $join, $name = null)
  515. {
  516. if (!in_array($join, $this->joins)) { // compare equality, NOT identity
  517. $this->joins[$name] = $join;
  518. }
  519. return $this;
  520. }
  521. /**
  522. * Adds a JOIN clause to the query and hydrates the related objects
  523. * Shortcut for $c->join()->with()
  524. * <code>
  525. * $c->joinWith('Book.Author');
  526. * => $c->join('Book.Author');
  527. * => $c->with('Author');
  528. * $c->joinWith('Book.Author a', Criteria::RIGHT_JOIN);
  529. * => $c->join('Book.Author a', Criteria::RIGHT_JOIN);
  530. * => $c->with('a');
  531. * </code>
  532. *
  533. * @param string $relation Relation to use for the join
  534. * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
  535. *
  536. * @return ModelCriteria The current object, for fluid interface
  537. */
  538. public function joinWith($relation, $joinType = Criteria::INNER_JOIN)
  539. {
  540. $this->join($relation, $joinType);
  541. $this->with(self::getRelationName($relation));
  542. return $this;
  543. }
  544. /**
  545. * Adds a relation to hydrate together with the main object
  546. * The relation must be initialized via a join() prior to calling with()
  547. * Examples:
  548. * <code>
  549. * $c->join('Book.Author');
  550. * $c->with('Author');
  551. *
  552. * $c->join('Book.Author a', Criteria::RIGHT_JOIN);
  553. * $c->with('a');
  554. * </code>
  555. * WARNING: on a one-to-many relationship, the use of with() combined with limit()
  556. * will return a wrong number of results for the related objects
  557. *
  558. * @param string $relation Relation to use for the join
  559. *
  560. * @return ModelCriteria The current object, for fluid interface
  561. */
  562. public function with($relation)
  563. {
  564. if (!isset($this->joins[$relation])) {
  565. throw new PropelException('Unknown relation name or alias ' . $relation);
  566. }
  567. $join = $this->joins[$relation];
  568. if ($join->getRelationMap()->getType() == RelationMap::MANY_TO_MANY) {
  569. throw new PropelException('with() does not allow hydration for many-to-many relationships');
  570. } elseif ($join->getRelationMap()->getType() == RelationMap::ONE_TO_MANY) {
  571. // For performance reasons, the formatters will use a special routine in this case
  572. $this->isWithOneToMany = true;
  573. }
  574. // check that the columns of the main class are already added (but only if this isn't a useQuery)
  575. if (!$this->hasSelectClause() && !$this->getPrimaryCriteria()) {
  576. $this->addSelfSelectColumns();
  577. }
  578. // add the columns of the related class
  579. $this->addRelationSelectColumns($relation);
  580. // list the join for later hydration in the formatter
  581. $this->with[$relation] = $join;
  582. return $this;
  583. }
  584. /**
  585. * Gets the array of ModelWith specifying which objects must be hydrated
  586. * together with the main object.
  587. *
  588. * @see with()
  589. * @return array
  590. */
  591. public function getWith()
  592. {
  593. return $this->with;
  594. }
  595. public function isWithOneToMany()
  596. {
  597. return $this->isWithOneToMany;
  598. }
  599. /**
  600. * Adds a supplementary column to the select clause
  601. * These columns can later be retrieved from the hydrated objects using getVirtualColumn()
  602. *
  603. * @param string $clause The SQL clause with object model column names
  604. * e.g. 'UPPER(Author.FirstName)'
  605. * @param string $name Optional alias for the added column
  606. * If no alias is provided, the clause is used as a column alias
  607. * This alias is used for retrieving the column via BaseObject::getVirtualColumn($alias)
  608. *
  609. * @return ModelCriteria The current object, for fluid interface
  610. */
  611. public function withColumn($clause, $name = null)
  612. {
  613. if (null === $name) {
  614. $name = str_replace(array('.', '(', ')'), '', $clause);
  615. }
  616. $clause = trim($clause);
  617. $this->replaceNames($clause);
  618. // check that the columns of the main class are already added (if this is the primary ModelCriteria)
  619. if (!$this->hasSelectClause() && !$this->getPrimaryCriteria()) {
  620. $this->addSelfSelectColumns();
  621. }
  622. $this->addAsColumn($name, $clause);
  623. return $this;
  624. }
  625. /**
  626. * Initializes a secondary ModelCriteria object, to be later merged with the current object
  627. *
  628. * @see ModelCriteria::endUse()
  629. * @param string $relationName Relation name or alias
  630. * @param string $secondCriteriaClass Classname for the ModelCriteria to be used
  631. *
  632. * @return ModelCriteria The secondary criteria object
  633. */
  634. public function useQuery($relationName, $secondaryCriteriaClass = null)
  635. {
  636. if (!isset($this->joins[$relationName])) {
  637. throw new PropelException('Unknown class or alias ' . $relationName);
  638. }
  639. $className = $this->joins[$relationName]->getTableMap()->getPhpName();
  640. if (null === $secondaryCriteriaClass) {
  641. $secondaryCriteria = PropelQuery::from($className);
  642. } else {
  643. $secondaryCriteria = new $secondaryCriteriaClass();
  644. }
  645. if ($className != $relationName) {
  646. $secondaryCriteria->setModelAlias($relationName, $relationName == $this->joins[$relationName]->getRelationMap()->getName() ? false : true);
  647. }
  648. $secondaryCriteria->setPrimaryCriteria($this, $this->joins[$relationName]);
  649. return $secondaryCriteria;
  650. }
  651. /**
  652. * Finalizes a secondary criteria and merges it with its primary Criteria
  653. *
  654. * @see Criteria::mergeWith()
  655. *
  656. * @return ModelCriteria The primary criteria object
  657. */
  658. public function endUse()
  659. {
  660. if (isset($this->aliases[$this->modelAlias])) {
  661. $this->removeAlias($this->modelAlias);
  662. }
  663. $primaryCriteria = $this->getPrimaryCriteria();
  664. $primaryCriteria->mergeWith($this);
  665. return $primaryCriteria;
  666. }
  667. /**
  668. * Add the content of a Criteria to the current Criteria
  669. * In case of conflict, the current Criteria keeps its properties
  670. * @see Criteria::mergeWith()
  671. *
  672. * @param Criteria $criteria The criteria to read properties from
  673. * @param string $operator The logical operator used to combine conditions
  674. * Defaults to Criteria::LOGICAL_AND, also accapts Criteria::LOGICAL_OR
  675. *
  676. * @return ModelCriteria The primary criteria object
  677. */
  678. public function mergeWith(Criteria $criteria, $operator = Criteria::LOGICAL_AND)
  679. {
  680. parent::mergeWith($criteria, $operator);
  681. // merge with
  682. if ($criteria instanceof ModelCriteria) {
  683. $this->with = array_merge($this->getWith(), $criteria->getWith());
  684. }
  685. return $this;
  686. }
  687. /**
  688. * Clear the conditions to allow the reuse of the query object.
  689. * The ModelCriteria's Model and alias 'all the properties set by construct) will remain.
  690. *
  691. * @return ModelCriteria The primary criteria object
  692. */
  693. public function clear()
  694. {
  695. parent::clear();
  696. $this->with = array();
  697. $this->primaryCriteria = null;
  698. $this->formatter=null;
  699. return $this;
  700. }
  701. /**
  702. * Sets the primary Criteria for this secondary Criteria
  703. *
  704. * @param ModelCriteria $criteria The primary criteria
  705. * @param Join $previousJoin The previousJoin for this ModelCriteria
  706. */
  707. public function setPrimaryCriteria(ModelCriteria $criteria, Join $previousJoin)
  708. {
  709. $this->primaryCriteria = $criteria;
  710. $this->setPreviousJoin($previousJoin);
  711. }
  712. /**
  713. * Gets the primary criteria for this secondary Criteria
  714. *
  715. * @return ModelCriteria The primary criteria
  716. */
  717. public function getPrimaryCriteria()
  718. {
  719. return $this->primaryCriteria;
  720. }
  721. /**
  722. * Adds the select columns for a the current table
  723. *
  724. * @return ModelCriteria The current object, for fluid interface
  725. */
  726. public function addSelfSelectColumns()
  727. {
  728. call_user_func(array($this->modelPeerName, 'addSelectColumns'), $this, $this->useAliasInSQL ? $this->modelAlias : null);
  729. return $this;
  730. }
  731. /**
  732. * Adds the select columns for a relation
  733. *
  734. * @param string $relation The relation name or alias, as defined in join()
  735. *
  736. * @return ModelCriteria The current object, for fluid interface
  737. */
  738. public function addRelationSelectColumns($relation)
  739. {
  740. $join = $this->joins[$relation];
  741. call_user_func(array($join->getTableMap()->getPeerClassname(), 'addSelectColumns'), $this, $join->getRelationAlias());
  742. return $this;
  743. }
  744. /**
  745. * Returns the class and alias of a string representing a model or a relation
  746. * e.g. 'Book b' => array('Book', 'b')
  747. * e.g. 'Book' => array('Book', null)
  748. *
  749. * @param string $class The classname to explode
  750. *
  751. * @return array list($className, $aliasName)
  752. */
  753. public static function getClassAndAlias($class)
  754. {
  755. if(strpos($class, ' ') !== false) {
  756. list($class, $alias) = explode(' ', $class);
  757. } else {
  758. $alias = null;
  759. }
  760. return array($class, $alias);
  761. }
  762. /**
  763. * Returns the name of a relation from a string.
  764. * The input looks like '$leftName.$relationName $relationAlias'
  765. *
  766. * @param string $relation Relation to use for the join
  767. * @return string the relationName used in the join
  768. */
  769. public static function getRelationName($relation)
  770. {
  771. // get the relationName
  772. list($fullName, $relationAlias) = self::getClassAndAlias($relation);
  773. if ($relationAlias) {
  774. $relationName = $relationAlias;
  775. } elseif (false === strpos($fullName, '.')) {
  776. $relationName = $fullName;
  777. } else {
  778. list($leftName, $relationName) = explode('.', $fullName);
  779. }
  780. return $relationName;
  781. }
  782. /**
  783. * Triggers the automated cloning on termination.
  784. * By default, temrination methods don't clone the current object,
  785. * even though they modify it. If the query must be reused after termination,
  786. * you must call this method prior to temrination.
  787. *
  788. * @param boolean $isKeepQuery
  789. *
  790. * @return ModelCriteria The current object, for fluid interface
  791. */
  792. public function keepQuery($isKeepQuery = true)
  793. {
  794. $this->isKeepQuery = (bool) $isKeepQuery;
  795. return $this;
  796. }
  797. /**
  798. * Checks whether the automated cloning on termination is enabled.
  799. *
  800. * @return boolean true if cloning must be done before termination
  801. */
  802. public function isKeepQuery()
  803. {
  804. return $this->isKeepQuery;
  805. }
  806. /**
  807. * Code to execute before every SELECT statement
  808. *
  809. * @param PropelPDO $con The connection object used by the query
  810. */
  811. protected function basePreSelect(PropelPDO $con)
  812. {
  813. return $this->preSelect($con);
  814. }
  815. protected function preSelect(PropelPDO $con)
  816. {
  817. }
  818. /**
  819. * Issue a SELECT query based on the current ModelCriteria
  820. * and format the list of results with the current formatter
  821. * By default, returns an array of model objects
  822. *
  823. * @param PropelPDO $con an optional connection object
  824. *
  825. * @return PropelObjectCollection|array|mixed the list of results, formatted by the current formatter
  826. */
  827. public function find($con = null)
  828. {
  829. $criteria = $this->isKeepQuery() ? clone $this : $this;
  830. $stmt = $criteria->getSelectStatement($con);
  831. return $criteria->getFormatter()->init($criteria)->format($stmt);
  832. }
  833. /**
  834. * Issue a SELECT ... LIMIT 1 query based on the current ModelCriteria
  835. * and format the result with the current formatter
  836. * By default, returns a model object
  837. *
  838. * @param PropelPDO $con an optional connection object
  839. *
  840. * @return mixed the result, formatted by the current formatter
  841. */
  842. public function findOne($con = null)
  843. {
  844. $criteria = $this->isKeepQuery() ? clone $this : $this;
  845. $criteria->limit(1);
  846. $stmt = $criteria->getSelectStatement($con);
  847. return $criteria->getFormatter()->init($criteria)->formatOne($stmt);
  848. }
  849. /**
  850. * Issue a SELECT ... LIMIT 1 query based on the current ModelCriteria
  851. * and format the result with the current formatter
  852. * By default, returns a model object
  853. *
  854. * @param PropelPDO $con an optional connection object
  855. *
  856. * @return mixed the result, formatted by the current formatter
  857. */
  858. public function findOneOrCreate($con = null)
  859. {
  860. $criteria = $this->isKeepQuery() ? clone $this : $this;
  861. $criteria->limit(1);
  862. $stmt = $criteria->getSelectStatement($con);
  863. if (!$ret = $this->findOne($con)) {
  864. $class = $this->getModelName();
  865. $obj = new $class();
  866. foreach ($this->keys() as $key) {
  867. $obj->setByName($key, $this->getValue($key), BasePeer::TYPE_COLNAME);
  868. }
  869. $ret = $this->getFormatter()->formatRecord($obj);
  870. }
  871. return $ret;
  872. }
  873. /**
  874. * Find object by primary key
  875. * Behaves differently if the model has simple or composite primary key
  876. * <code>
  877. * // simple primary key
  878. * $book = $c->findPk(12, $con);
  879. * // composite primary key
  880. * $bookOpinion = $c->findPk(array(34, 634), $con);
  881. * </code>
  882. * @param mixed $key Primary key to use for the query
  883. * @param PropelPDO $con an optional connection object
  884. *
  885. * @return mixed the result, formatted by the current formatter
  886. */
  887. public function findPk($key, $con = null)
  888. {
  889. $pkCols = $this->getTableMap()->getPrimaryKeyColumns();
  890. if (count($pkCols) == 1) {
  891. // simple primary key
  892. $pkCol = $pkCols[0];
  893. $this->add($pkCol->getFullyQualifiedName(), $key);
  894. return $this->findOne($con);
  895. } else {
  896. // composite primary key
  897. foreach ($pkCols as $pkCol) {
  898. $keyPart = array_shift($key);
  899. $this->add($pkCol->getFullyQualifiedName(), $keyPart);
  900. }
  901. return $this->findOne($con);
  902. }
  903. }
  904. /**
  905. * Find objects by primary key
  906. * Behaves differently if the model has simple or composite primary key
  907. * <code>
  908. * // simple primary key
  909. * $books = $c->findPks(array(12, 56, 832), $con);
  910. * // composite primary key
  911. * $bookOpinion = $c->findPks(array(array(34, 634), array(45, 518), array(34, 765)), $con);
  912. * </code>
  913. * @param array $keys Primary keys to use for the query
  914. * @param PropelPDO $con an optional connection object
  915. *
  916. * @return mixed the list of results, formatted by the current formatter
  917. */
  918. public function findPks($keys, $con = null)
  919. {
  920. $pkCols = $this->getTableMap()->getPrimaryKeyColumns();
  921. if (count($pkCols) == 1) {
  922. // simple primary key
  923. $pkCol = array_shift($pkCols);
  924. $this->add($pkCol->getFullyQualifiedName(), $keys, Criteria::IN);
  925. } else {
  926. // composite primary key
  927. throw new PropelException('Multiple object retrieval is not implemented for composite primary keys');
  928. }
  929. return $this->find($con);
  930. }
  931. protected function getSelectStatement($con = null)
  932. {
  933. $dbMap = Propel::getDatabaseMap($this->getDbName());
  934. $db = Propel::getDB($this->getDbName());
  935. if ($con === null) {
  936. $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ);
  937. }
  938. // check that the columns of the main class are already added (if this is the primary ModelCriteria)
  939. if (!$this->hasSelectClause() && !$this->getPrimaryCriteria()) {
  940. $this->addSelfSelectColumns();
  941. }
  942. $con->beginTransaction();
  943. try {
  944. $this->basePreSelect($con);
  945. $params = array();
  946. $sql = BasePeer::createSelectSql($this, $params);
  947. $stmt = $con->prepare($sql);
  948. BasePeer::populateStmtValues($stmt, $params, $dbMap, $db);
  949. $stmt->execute();
  950. $con->commit();
  951. } catch (Exception $e) {
  952. if ($stmt) {
  953. $stmt = null; // close
  954. }
  955. $con->rollBack();
  956. Propel::log($e->getMessage(), Propel::LOG_ERR);
  957. throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), $e);
  958. }
  959. return $stmt;
  960. }
  961. /**
  962. * Apply a condition on a column and issues the SELECT query
  963. *
  964. * @see filterBy()
  965. * @see find()
  966. *
  967. * @param string $column A string representing the column phpName, e.g. 'AuthorId'
  968. * @param mixed $value A value for the condition
  969. * @param PropelPDO $con An optional connection object
  970. *
  971. * @return mixed the list of results, formatted by the current formatter
  972. */
  973. public function findBy($column, $value, $con = null)
  974. {
  975. $method = 'filterBy' . $column;
  976. $this->$method($value);
  977. return $this->find($con);
  978. }
  979. /**
  980. * Apply a list of conditions on columns and issues the SELECT query
  981. * <code>
  982. * $c->findByArray(array(
  983. * 'Title' => 'War And Peace',
  984. * 'Publisher' => $publisher
  985. * ), $con);
  986. * </code>
  987. *
  988. * @see filterByArray()
  989. * @see find()
  990. *
  991. * @param mixed $conditions An array of conditions, using column phpNames as key
  992. * @param PropelPDO $con an optional connection object
  993. *
  994. * @return mixed the list of results, formatted by the current formatter
  995. */
  996. public function findByArray($conditions, $con = null)
  997. {
  998. $this->filterByArray($conditions);
  999. return $this->find($con);
  1000. }
  1001. /**
  1002. * Apply a condition on a column and issues the SELECT ... LIMIT 1 query
  1003. *
  1004. * @see filterBy()
  1005. * @see findOne()
  1006. *
  1007. * @param mixed $column A string representing thecolumn phpName, e.g. 'AuthorId'
  1008. * @param mixed $value A value for the condition
  1009. * @param PropelPDO $con an optional connection object
  1010. *
  1011. * @return mixed the result, formatted by the current formatter
  1012. */
  1013. public function findOneBy($column, $value, $con = null)
  1014. {
  1015. $method = 'filterBy' . $column;
  1016. $this->$method($value);
  1017. return $this->findOne($con);
  1018. }
  1019. /**
  1020. * Apply a list of conditions on columns and issues the SELECT ... LIMIT 1 query
  1021. * <code>
  1022. * $c->findOneByArray(array(
  1023. * 'Title' => 'War And Peace',
  1024. * 'Publisher' => $publisher
  1025. * ), $con);
  1026. * </code>
  1027. *
  1028. * @see filterByArray()
  1029. * @see findOne()
  1030. *
  1031. * @param mixed $conditions An array of conditions, using column phpNames as key
  1032. * @param PropelPDO $con an optional connection object
  1033. *
  1034. * @return mixed the list of results, formatted by the current formatter
  1035. */
  1036. public function findOneByArray($conditions, $con = null)
  1037. {
  1038. $this->filterByArray($conditions);
  1039. return $this->findOne($con);
  1040. }
  1041. /**
  1042. * Issue a SELECT COUNT(*) query based on the current ModelCriteria
  1043. *
  1044. * @param PropelPDO $con an optional connection object
  1045. *
  1046. * @return integer the number of results
  1047. */
  1048. public function count($con = null)
  1049. {
  1050. if ($con === null) {
  1051. $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ);
  1052. }
  1053. $criteria = $this->isKeepQuery() ? clone $this : $this;
  1054. $criteria->setDbName($this->getDbName()); // Set the correct dbName
  1055. $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count
  1056. // We need to set the primary table name, since in the case that there are no WHERE columns
  1057. // it will be impossible for the BasePeer::createSelectSql() method to determine which
  1058. // tables go into the FROM clause.
  1059. $criteria->setPrimaryTableName(constant($this->modelPeerName.'::TABLE_NAME'));
  1060. $stmt = $criteria->getCountStatement($con);
  1061. if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
  1062. $count = (int) $row[0];
  1063. } else {
  1064. $count = 0; // no rows returned; we infer that means 0 matches.
  1065. }
  1066. $stmt->closeCursor();
  1067. return $count;
  1068. }
  1069. protected function getCountStatement($con = null)
  1070. {
  1071. $dbMap = Propel::getDatabaseMap($this->getDbName());
  1072. $db = Propel::getDB($this->getDbName());
  1073. if ($con === null) {
  1074. $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ);
  1075. }
  1076. // check that the columns of the main class are already added (if this is the primary ModelCriteria)
  1077. if (!$this->hasSelectClause() && !$this->getPrimaryCriteria()) {
  1078. $this->addSelfSelectColumns();
  1079. }
  1080. $needsComplexCount = $this->getGroupByColumns()
  1081. || $this->getOffset()
  1082. || $this->getLimit()
  1083. || $this->getHaving()
  1084. || in_array(Criteria::DISTINCT, $this->getSelectModifiers());
  1085. $con->beginTransaction();
  1086. try {
  1087. $this->basePreSelect($con);
  1088. $params = array();
  1089. if ($needsComplexCount) {
  1090. if (BasePeer::needsSelectAliases($this)) {
  1091. if ($this->getHaving()) {
  1092. throw new PropelException('Propel cannot create a COUNT query when using HAVING and duplicate column names in the SELECT part');
  1093. }
  1094. BasePeer::turnSelectColumnsToAliases($this);
  1095. }
  1096. $selectSql = BasePeer::createSelectSql($this, $params);
  1097. $sql = 'SELECT COUNT(*) FROM (' . $selectSql . ') propelmatch4cnt';
  1098. } else {
  1099. // Replace SELECT columns with COUNT(*)
  1100. $this->clearSelectColumns()->addSelectColumn('COUNT(*)');
  1101. $sql = BasePeer::createSelectSql($this, $params);
  1102. }
  1103. $stmt = $con->prepare($sql);
  1104. BasePeer::populateStmtValues($stmt, $params, $dbMap, $db);
  1105. $stmt->execute();
  1106. $con->commit();
  1107. } catch (PropelException $e) {
  1108. $con->rollback();
  1109. throw $e;
  1110. }
  1111. return $stmt;
  1112. }
  1113. /**
  1114. * Issue a SELECT query based on the current ModelCriteria
  1115. * and uses a page and a maximum number of results per page
  1116. * to compute an offet and a limit.
  1117. *
  1118. * @param int $page number of the page to start the pager on. Page 1 means no offset
  1119. * @param int $maxPerPage maximum number of results per page. Determines the limit
  1120. * @param PropelPDO $con an optional connection object
  1121. *
  1122. * @return PropelModelPager a pager object, supporting iteration
  1123. */
  1124. public function paginate($page = 1, $maxPerPage = 10, $con = null)
  1125. {
  1126. $criteria = $this->isKeepQuery() ? clone $this : $this;
  1127. $pager = new PropelModelPager($criteria, $maxPerPage);
  1128. $pager->setPage($page);
  1129. $pager->init();
  1130. return $pager;
  1131. }
  1132. /**
  1133. * Code to execute before every DELETE statement
  1134. *
  1135. * @param PropelPDO $con The connection object used by the query
  1136. */
  1137. protected function basePreDelete(PropelPDO $con)
  1138. {
  1139. return $this->preDelete($con);
  1140. }
  1141. protected function preDelete(PropelPDO $con)
  1142. {
  1143. }
  1144. /**
  1145. * Code to execute after every DELETE statement
  1146. *
  1147. * @param int $affectedRows the number of deleted rows
  1148. * @param PropelPDO $con The connection object used by the query
  1149. */
  1150. protected function basePostDelete($affectedRows, PropelPDO $con)
  1151. {
  1152. return $this->postDelete($affectedRows, $con);
  1153. }
  1154. protected function postDelete($affectedRows, PropelPDO $con)
  1155. {
  1156. }
  1157. /**
  1158. * Issue a DELETE query based on the current ModelCriteria
  1159. * An optional hook on basePreDelete() can prevent the actual deletion
  1160. *
  1161. * @param PropelPDO $con an optional connection object
  1162. *
  1163. * @return integer the number of deleted rows
  1164. */
  1165. public function delete($con = null)
  1166. {
  1167. if (count($this->getMap()) == 0) {
  1168. throw new PropelException('delete() expects a Criteria with at least one condition. Use deleteAll() to delete all the rows of a table');
  1169. }
  1170. if ($con === null) {
  1171. $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ);
  1172. }
  1173. $criteria = $this->isKeepQuery() ? clone $this : $this;
  1174. $criteria->setDbName($this->getDbName());
  1175. $con->beginTransaction();
  1176. try {
  1177. if(!$affectedRows = $criteria->basePreDelete($con)) {
  1178. $affectedRows = $criteria->doDelete($con);
  1179. }
  1180. $criteria->basePostDelete($affectedRows, $con);
  1181. $con->commit();
  1182. } catch (PropelException $e) {
  1183. $con->rollback();
  1184. throw $e;
  1185. }
  1186. return $affectedRows;
  1187. }
  1188. /**
  1189. * Issue a DELETE query based on the current ModelCriteria
  1190. * This method is called by ModelCriteria::delete() inside a transaction
  1191. *
  1192. * @param PropelPDO $con a connection object
  1193. *
  1194. * @return integer the number of deleted rows
  1195. */
  1196. public function doDelete($con)
  1197. {
  1198. $affectedRows = call_user_func(array($this->modelPeerName, 'doDelete'), $this, $con);
  1199. return $affectedRows;
  1200. }
  1201. /**
  1202. * Issue a DELETE query based on the current ModelCriteria deleting all rows in the table
  1203. * An optional hook on basePreDelete() can prevent the actual deletion
  1204. *
  1205. * @param PropelPDO $con an optional connection object
  1206. *
  1207. * @return integer the number of deleted rows
  1208. */
  1209. public function deleteAll($con = null)
  1210. {
  1211. if ($con === null) {
  1212. $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_WRITE);
  1213. }
  1214. $con->beginTransaction();
  1215. try {
  1216. if(!$affectedRows = $this->basePreDelete($con)) {
  1217. $affectedRows = $this->doDeleteAll($con);
  1218. }
  1219. $this->basePostDelete($affectedRows, $con);
  1220. $con->commit();
  1221. return $affectedRows;
  1222. } catch (PropelException $e) {
  1223. $con->rollBack();
  1224. throw $e;
  1225. }
  1226. return $affectedRows;
  1227. }
  1228. /**
  1229. * Issue a DELETE query based on the current ModelCriteria deleting all rows in the table
  1230. * This method is called by ModelCriteria::deleteAll() inside a transaction
  1231. *
  1232. * @param PropelPDO $con a connection object
  1233. *
  1234. * @return integer the number of deleted rows
  1235. */
  1236. public function doDeleteAll($con)
  1237. {
  1238. $affectedRows = call_user_func(array($this->modelPeerName, 'doDeleteAll'), $con);
  1239. return $affectedRows;
  1240. }
  1241. /**
  1242. * Code to execute before every UPDATE statement
  1243. *
  1244. * @param array $values The associatiove array of columns and values for the update
  1245. * @param PropelPDO $con The connection object used by the query
  1246. * @param boolean $forceIndividualSaves If false (default), the resulting call is a BasePeer::doUpdate(), ortherwise it is a series of save() calls on all the found objects
  1247. */
  1248. protected function basePreUpdate(&$values, PropelPDO $con, $forceIndividualSaves = false)
  1249. {
  1250. return $this->preUpdate($values, $con, $forceIndividualSaves);
  1251. }
  1252. protected function preUpdate(&$values, PropelPDO $con, $forceIndividualSaves = false)
  1253. {
  1254. }
  1255. /**
  1256. * Code to execute after every UPDATE statement
  1257. *
  1258. * @param int $affectedRows the number of updated rows
  1259. * @param PropelPDO $con The connection object used by the query
  1260. */
  1261. protected function basePostUpdate($affectedRows, PropelPDO $con)
  1262. {
  1263. return $this->postUpdate($affectedRows, $con);
  1264. }
  1265. protected function postUpdate($affectedRows, PropelPDO $con)
  1266. {
  1267. }
  1268. /**
  1269. * Issue an UPDATE query based the current ModelCriteria and a list of changes.
  1270. * An optional hook on basePreUpdate() can prevent the actual update.
  1271. * Beware that behaviors based on hooks in the object's save() method
  1272. * will only be triggered if you force individual saves, i.e. if you pass true as second argument.
  1273. *
  1274. * @param array $values Associative array of keys and values to replace
  1275. * @param PropelPDO $con an optional connection object
  1276. * @param boolean $forceIndividualSaves If false (default), the resulting call is a BasePeer::doUpdate(), ortherwise it is a series of save() calls on all the found objects
  1277. *
  1278. * @return Integer Number of updated rows
  1279. */
  1280. public function update($values, $con = null, $forceIndividualSaves = false)
  1281. {
  1282. if (!is_array($values)) {
  1283. throw new PropelException('set() expects an array as first argument');
  1284. }
  1285. if (count($this->getJoins())) {
  1286. throw new PropelException('set() does not support multitable updates, please do not use join()');
  1287. }
  1288. if ($con === null) {
  1289. $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_WRITE);
  1290. }
  1291. $criteria = $this->isKeepQuery() ? clone $this : $this;
  1292. $criteria->setPrimaryTableName(constant($this->modelPeerName.'::TABLE_NAME'));
  1293. $con->beginTransaction();
  1294. try {
  1295. if(!$affectedRows = $criteria->basePreUpdate($values, $con, $forceIndividualSaves)) {
  1296. $affectedRows = $criteria->doUpdate($values, $con, $forceIndividualSaves);
  1297. }
  1298. $criteria->basePostUpdate($affectedRows, $con);
  1299. $con->commit();
  1300. } catch (PropelException $e) {
  1301. $con->rollBack();
  1302. throw $e;
  1303. }
  1304. return $affectedRows;
  1305. }
  1306. /**
  1307. * Issue an UPDATE query based the current ModelCriteria and a list of changes.
  1308. * This method is called by ModelCriteria::update() inside a transaction.
  1309. *
  1310. * @param array $values Associative array of keys and values to replace
  1311. * @param PropelPDO $con a connection object
  1312. * @param boolean $forceIndividualSaves If false (default), the resulting call is a BasePeer::doUpdate(), ortherwise it is a series of save() calls on all the found objects
  1313. *
  1314. * @return Integer Number of updated rows
  1315. */
  1316. public function doUpdate($values, $con, $forceIndividualSaves = false)
  1317. {
  1318. if($forceIndividualSaves) {
  1319. // Update rows one by one
  1320. $objects = $this->setFormatter(ModelCriteria::FORMAT_OBJECT)->find($con);
  1321. foreach ($objects as $object) {
  1322. foreach ($values as $key => $value) {
  1323. $object->setByName($key, $value);
  1324. }
  1325. }
  1326. $objects->save($con);
  1327. $affectedRows = count($objects);
  1328. } else {
  1329. // update rows in a single query
  1330. $set = new Criteria();
  1331. foreach ($values as $columnName => $value) {
  1332. $realColumnName = $this->getTableMap()->getColumnByPhpName($columnName)->getFullyQualifiedName();
  1333. $set->add($realColumnName, $value);
  1334. }
  1335. $affectedRows = BasePeer::doUpdate($this, $set, $con);
  1336. call_user_func(array($this->modelPeerName, 'clearInstancePool'));
  1337. call_user_func(array($this->modelPeerName, 'clearRelatedInstancePool'));
  1338. }
  1339. return $affectedRows;
  1340. }
  1341. /**
  1342. * Creates a Criterion object based on a list of existing condition names and a comparator
  1343. *
  1344. * @param array $conditions The list of condition names, e.g. array('cond1', 'cond2')
  1345. * @param string $comparator A comparator, Criteria::LOGICAL_AND (default) or Criteria::LOGICAL_OR
  1346. *
  1347. * @return Criterion a Criterion or ModelCriterion object
  1348. */
  1349. protected function getCriterionForConditions($conditions, $comparator = null)
  1350. {
  1351. $comparator = (null === $comparator) ? Criteria::LOGICAL_AND : $comparator;
  1352. $this->combine($conditions, $comparator, 'propel_temp_name');
  1353. $criterion = $this->namedCriterions['propel_temp_name'];
  1354. unset($this->namedCriterions['propel_temp_name']);
  1355. return $criterion;
  1356. }
  1357. /**
  1358. * Creates a Criterion object based on a SQL clause and a value
  1359. * Uses introspection to translate the column phpName into a fully qualified name
  1360. *
  1361. * @param string $clause The pseudo SQL clause, e.g. 'AuthorId = ?'
  1362. * @param mixed $value A value for the condition
  1363. *
  1364. * @return Criterion a Criterion or ModelCriterion object
  1365. */
  1366. protected function getCriterionForClause($clause, $value)
  1367. {
  1368. $clause = trim($clause);
  1369. if($this->replaceNames($clause)) {
  1370. // at least one column name was found and replaced in the clause
  1371. // this is enough to determine the type to bind the parameter to
  1372. if (preg_match('/IN \?$/i', $clause) !== 0) {
  1373. $operator = ModelCriteria::MODEL_CLAUSE_ARRAY;
  1374. } elseif (preg_match('/LIKE \?$/i', $clause) !== 0) {
  1375. $operator = ModelCriteria::MODEL_CLAUSE_LIKE;
  1376. } elseif (substr_count($clause, '?') > 1) {
  1377. $operator = ModelCriteria::MODEL_CLAUSE_SEVERAL;
  1378. } else {
  1379. $operator = ModelCriteria::MODEL_CLAUSE;
  1380. }
  1381. $criterion = new ModelCriterion($this, $this->replacedColumns[0], $value, $operator, $clause);
  1382. if ($this->currentAlias != '') {
  1383. $criterion->setTable($this->currentAlias);
  1384. }
  1385. } else {
  1386. // no column match in clause, must be an expression like '1=1'
  1387. if (strpos($clause, '?') !== false) {
  1388. throw new PropelException("Cannot determine the column to bind to the parameter in clause '$clause'");
  1389. }
  1390. $criterion = new Criterion($this, null, $clause, Criteria::CUSTOM);
  1391. }
  1392. return $criterion;
  1393. }
  1394. /**
  1395. * Replaces complete column names (like Article.AuthorId) in an SQL clause
  1396. * by their exact Propel column fully qualified name (e.g. article.AUTHOR_ID)
  1397. * but ignores the column names inside quotes
  1398. *
  1399. * Note: if you know a way to do so in one step, and in an efficient way, I'm interested :)
  1400. *
  1401. * @param string $clause SQL clause to inspect (modified by the method)
  1402. *
  1403. * @return boolean Whether the method managed to find and replace at least one column name
  1404. */
  1405. protected function replaceNames(&$clause)
  1406. {
  1407. $this->replacedColumns = array();
  1408. $this->currentAlias = '';
  1409. $this->foundMatch = false;
  1410. $regexp = <<<EOT
  1411. |
  1412. (["'][^"']*?["'])? # string
  1413. ([^"']+)? # not string
  1414. |x
  1415. EOT;
  1416. $clause = preg_replace_callback($regexp, array($this, 'doReplaceName'), $clause);
  1417. return $this->foundMatch;
  1418. }
  1419. /**
  1420. * Callback function to replace expressions containing column names with expressions using the real column names
  1421. * Handles strings properly
  1422. * e.g. 'CONCAT(Book.Title, "Book.Title") = ?'
  1423. * => 'CONCAT(book.TITLE, "Book.Title") = ?'
  1424. *
  1425. * @param array $matches Matches found by preg_replace_callback
  1426. *
  1427. * @return string the expression replacement
  1428. */
  1429. protected function doReplaceName($matches)
  1430. {
  1431. if(!$matches[0]) {
  1432. return '';
  1433. }
  1434. // replace names only in expressions, not in strings delimited by quotes
  1435. return $matches[1] . preg_replace_callback('/\w+\.\w+/', array($this, 'doReplaceNameInExpression'), $matches[2]);
  1436. }
  1437. /**
  1438. * Callback function to replace column names by their real name in a clause
  1439. * e.g. 'Book.Title IN ?'
  1440. * => 'book.TITLE IN ?'
  1441. *
  1442. * @param array $matches Matches found by preg_replace_callback
  1443. *
  1444. * @return string the column name replacement
  1445. */
  1446. protected function doReplaceNameInExpression($matches)
  1447. {
  1448. $key = $matches[0];
  1449. list($column, $realColumnName) = $this->getColumnFromName($key);
  1450. if ($column instanceof ColumnMap) {
  1451. $this->replacedColumns[]= $column;
  1452. $this->foundMatch = true;
  1453. return $realColumnName;
  1454. } else {
  1455. return $key;
  1456. }
  1457. }
  1458. /**
  1459. * Finds a column and a SQL translation for a pseudo SQL column name
  1460. * Respects table aliases previously registered in a join() or addAlias()
  1461. * Examples:
  1462. * <code>
  1463. * $c->getColumnFromName('Book.Title');
  1464. * => array($bookTitleColumnMap, 'book.TITLE')
  1465. * $c->join('Book.Author a')
  1466. * ->getColumnFromName('a.FirstName');
  1467. * => array($authorFirstNameColumnMap, 'a.FIRST_NAME')
  1468. * </code>
  1469. *
  1470. * @param string $phpName String representing the column name in a pseudo SQL clause, e.g. 'Book.Title'
  1471. *
  1472. * @return array List($columnMap, $realColumnName)
  1473. */
  1474. protected function getColumnFromName($phpName, $failSilently = true)
  1475. {
  1476. if (strpos($phpName, '.') === false) {
  1477. $class = $this->getModelAliasOrName();
  1478. } else {
  1479. list($class, $phpName) = explode('.', $phpName);
  1480. }
  1481. if ($class == $this->getModelAliasOrName()) {
  1482. // column of the Criteria's model
  1483. $tableMap = $this->getTableMap();
  1484. } elseif (isset($this->joins[$class])) {
  1485. // column of a relations's model
  1486. $tableMap = $this->joins[$class]->getTableMap();
  1487. } else {
  1488. if ($failSilently) {
  1489. return array(null, null);
  1490. } else {
  1491. throw new PropelException('Unknown model or alias ' . $class);
  1492. }
  1493. }
  1494. if ($tableMap->hasColumnByPhpName($phpName)) {
  1495. $column = $tableMap->getColumnByPhpName($phpName);
  1496. if (isset($this->aliases[$class])) {
  1497. $this->currentAlias = $class;
  1498. $realColumnName = $class . '.' . $column->getName();
  1499. } else {
  1500. $realColumnName = $column->getFullyQualifiedName();
  1501. }
  1502. return array($column, $realColumnName);
  1503. } elseif (isset($this->asColumns[$phpName])) {
  1504. // aliased column
  1505. return array(null, $phpName);
  1506. } else {
  1507. if ($failSilently) {
  1508. return array(null, null);
  1509. } else {
  1510. throw new PropelException('Unknown column ' . $phpName . ' on model or alias ' . $class);
  1511. }
  1512. }
  1513. }
  1514. /**
  1515. * Return a fully qualified column name corresponding to a simple column phpName
  1516. * Uses model alias if it exists
  1517. * Warning: restricted to the columns of the main model
  1518. * e.g. => 'Title' => 'book.TITLE'
  1519. *
  1520. * @param string $columnName the Column phpName, without the table name
  1521. *
  1522. * @return string the fully qualified column name
  1523. */
  1524. protected function getRealColumnName($columnName)
  1525. {
  1526. if (!$this->getTableMap()->hasColumnByPhpName($columnName)) {
  1527. throw new PropelException('Unkown column ' . $columnName . ' in model ' . $this->modelName);
  1528. }
  1529. if ($this->useAliasInSQL) {
  1530. return $this->modelAlias . '.' . $this->getTableMap()->getColumnByPhpName($columnName)->getName();
  1531. } else {
  1532. return $this->getTableMap()->getColumnByPhpName($columnName)->getFullyQualifiedName();
  1533. }
  1534. }
  1535. /**
  1536. * Changes the table part of a a fully qualified column name if a true model alias exists
  1537. * e.g. => 'book.TITLE' => 'b.TITLE'
  1538. * This is for use as first argument of Criteria::add()
  1539. *
  1540. * @param string $colName the fully qualified column name, e.g 'book.TITLE' or BookPeer::TITLE
  1541. *
  1542. * @return string the fully qualified column name, using table alias if applicatble
  1543. */
  1544. public function getAliasedColName($colName)
  1545. {
  1546. if ($this->useAliasInSQL) {
  1547. return $this->modelAlias . substr($colName, strpos($colName, '.'));
  1548. } else {
  1549. return $colName;
  1550. }
  1551. }
  1552. /**
  1553. * Overrides Criteria::add() to force the use of a true table alias if it exists
  1554. *
  1555. * @see Criteria::add()
  1556. * @param string $column The colName of column to run the comparison on (e.g. BookPeer::ID)
  1557. * @param mixed $value
  1558. * @param string $comparison A String.
  1559. *
  1560. * @return ModelCriteria A modified Criteria object.
  1561. */
  1562. public function addUsingAlias($p1, $value = null, $comparison = null)
  1563. {
  1564. $key = $this->getAliasedColName($p1);
  1565. return $this->containsKey($key) ? $this->addAnd($key, $value, $comparison) : $this->add($key, $value, $comparison);
  1566. }
  1567. /**
  1568. * Get all the parameters to bind to this criteria
  1569. * Does part of the job of BasePeer::createSelectSql() for the cache
  1570. *
  1571. * @return array list of parameters, each parameter being an array like
  1572. * array('table' => $realtable, 'column' => $column, 'value' => $value)
  1573. */
  1574. public function getParams()
  1575. {
  1576. $params = array();
  1577. $dbMap = Propel::getDatabaseMap($this->getDbName());
  1578. foreach ($this->getMap() as $criterion) {
  1579. $table = null;
  1580. foreach ($criterion->getAttachedCriterion() as $attachedCriterion) {
  1581. $tableName = $attachedCriterion->getTable();
  1582. $table = $this->getTableForAlias($tableName);
  1583. if (null === $table) {
  1584. $table = $tableName;
  1585. }
  1586. if (($this->isIgnoreCase() || $attachedCriterion->isIgnoreCase())
  1587. && $dbMap->getTable($table)->getColumn($attachedCriterion->getColumn())->isText()) {
  1588. $attachedCriterion->setIgnoreCase(true);
  1589. }
  1590. }
  1591. $sb = '';
  1592. $criterion->appendPsTo($sb, $params);
  1593. }
  1594. $having = $this->getHaving();
  1595. if ($having !== null) {
  1596. $sb = '';
  1597. $having->appendPsTo($sb, $params);
  1598. }
  1599. return $params;
  1600. }
  1601. /**
  1602. * Handle the magic
  1603. * Supports findByXXX(), findOneByXXX(), filterByXXX(), orderByXXX(), and groupByXXX() methods,
  1604. * where XXX is a column phpName.
  1605. * Supports XXXJoin(), where XXX is a join direction (in 'left', 'right', 'inner')
  1606. */
  1607. public function __call($name, $arguments)
  1608. {
  1609. // Maybe it's a magic call to one of the methods supporting it, e.g. 'findByTitle'
  1610. static $methods = array('findBy', 'findOneBy', 'filterBy', 'orderBy', 'groupBy');
  1611. foreach ($methods as $method)
  1612. {
  1613. if(strpos($name, $method) === 0)
  1614. {
  1615. $columns = substr($name, strlen($method));
  1616. if(in_array($method, array('findBy', 'findOneBy')) && strpos($columns, 'And') !== false) {
  1617. $method = $method . 'Array';
  1618. $columns = explode('And', $columns);
  1619. $conditions = array();
  1620. foreach ($columns as $column) {
  1621. $conditions[$column] = array_shift($arguments);
  1622. }
  1623. array_unshift($arguments, $conditions);
  1624. } else {
  1625. array_unshift($arguments, $columns);
  1626. }
  1627. return call_user_func_array(array($this, $method), $arguments);
  1628. }
  1629. }
  1630. // Maybe it's a magic call to a qualified joinWith method, e.g. 'leftJoinWith' or 'joinWithAuthor'
  1631. if(($pos = stripos($name, 'joinWith')) !== false) {
  1632. $type = substr($name, 0, $pos);
  1633. if(in_array($type, array('left', 'right', 'inner'))) {
  1634. $joinType = strtoupper($type) . ' JOIN';
  1635. } else {
  1636. $joinType = Criteria::INNER_JOIN;
  1637. }
  1638. if(!$relation = substr($name, $pos + 8)) {
  1639. $relation = $arguments[0];
  1640. }
  1641. return $this->joinWith($relation, $joinType);
  1642. }
  1643. // Maybe it's a magic call to a qualified join method, e.g. 'leftJoin'
  1644. if(($pos = strpos($name, 'Join')) > 0)
  1645. {
  1646. $type = substr($name, 0, $pos);
  1647. if(in_array($type, array('left', 'right', 'inner')))
  1648. {
  1649. $joinType = strtoupper($type) . ' JOIN';
  1650. // Test if first argument is suplied, else don't provide an alias to joinXXX (default value)
  1651. if (!isset($arguments[0])) {
  1652. $arguments[0] = '';
  1653. }
  1654. array_push($arguments, $joinType);
  1655. $method = substr($name, $pos);
  1656. // no lcfirst in php<5.3...
  1657. $method[0] = strtolower($method[0]);
  1658. return call_user_func_array(array($this, $method), $arguments);
  1659. }
  1660. }
  1661. throw new PropelException(sprintf('Undefined method %s::%s()', __CLASS__, $name));
  1662. }
  1663. /**
  1664. * Ensures deep cloning of attached objects
  1665. */
  1666. public function __clone()
  1667. {
  1668. parent::__clone();
  1669. foreach ($this->with as $key => $join) {
  1670. $this->with[$key] = clone $join;
  1671. }
  1672. if (null !== $this->formatter) {
  1673. $this->formatter = clone $this->formatter;
  1674. }
  1675. }
  1676. }