ManyToManyPersister.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\ORM\Persisters;
  20. use Doctrine\ORM\Mapping\ClassMetadata,
  21. Doctrine\ORM\PersistentCollection,
  22. Doctrine\ORM\UnitOfWork;
  23. /**
  24. * Persister for many-to-many collections.
  25. *
  26. * @author Roman Borschel <roman@code-factory.org>
  27. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  28. * @author Alexander <iam.asm89@gmail.com>
  29. * @since 2.0
  30. */
  31. class ManyToManyPersister extends AbstractCollectionPersister
  32. {
  33. /**
  34. * {@inheritdoc}
  35. *
  36. * @override
  37. */
  38. protected function _getDeleteRowSQL(PersistentCollection $coll)
  39. {
  40. $columns = array();
  41. $mapping = $coll->getMapping();
  42. $class = $this->_em->getClassMetadata(get_class($coll->getOwner()));
  43. foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) {
  44. $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
  45. }
  46. foreach ($mapping['joinTable']['inverseJoinColumns'] as $joinColumn) {
  47. $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
  48. }
  49. return 'DELETE FROM ' . $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform)
  50. . ' WHERE ' . implode(' = ? AND ', $columns) . ' = ?';
  51. }
  52. /**
  53. * {@inheritdoc}
  54. *
  55. * @override
  56. * @internal Order of the parameters must be the same as the order of the columns in
  57. * _getDeleteRowSql.
  58. */
  59. protected function _getDeleteRowSQLParameters(PersistentCollection $coll, $element)
  60. {
  61. return $this->_collectJoinTableColumnParameters($coll, $element);
  62. }
  63. /**
  64. * {@inheritdoc}
  65. *
  66. * @override
  67. */
  68. protected function _getUpdateRowSQL(PersistentCollection $coll)
  69. {}
  70. /**
  71. * {@inheritdoc}
  72. *
  73. * @override
  74. * @internal Order of the parameters must be the same as the order of the columns in
  75. * _getInsertRowSql.
  76. */
  77. protected function _getInsertRowSQL(PersistentCollection $coll)
  78. {
  79. $columns = array();
  80. $mapping = $coll->getMapping();
  81. $class = $this->_em->getClassMetadata(get_class($coll->getOwner()));
  82. $joinTable = $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform);
  83. foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) {
  84. $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
  85. }
  86. foreach ($mapping['joinTable']['inverseJoinColumns'] as $joinColumn) {
  87. $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
  88. }
  89. return 'INSERT INTO ' . $joinTable . ' (' . implode(', ', $columns) . ')'
  90. . ' VALUES (' . implode(', ', array_fill(0, count($columns), '?')) . ')';
  91. }
  92. /**
  93. * {@inheritdoc}
  94. *
  95. * @override
  96. * @internal Order of the parameters must be the same as the order of the columns in
  97. * _getInsertRowSql.
  98. */
  99. protected function _getInsertRowSQLParameters(PersistentCollection $coll, $element)
  100. {
  101. return $this->_collectJoinTableColumnParameters($coll, $element);
  102. }
  103. /**
  104. * Collects the parameters for inserting/deleting on the join table in the order
  105. * of the join table columns as specified in ManyToManyMapping#joinTableColumns.
  106. *
  107. * @param $coll
  108. * @param $element
  109. * @return array
  110. */
  111. private function _collectJoinTableColumnParameters(PersistentCollection $coll, $element)
  112. {
  113. $params = array();
  114. $mapping = $coll->getMapping();
  115. $isComposite = count($mapping['joinTableColumns']) > 2;
  116. $identifier1 = $this->_uow->getEntityIdentifier($coll->getOwner());
  117. $identifier2 = $this->_uow->getEntityIdentifier($element);
  118. if ($isComposite) {
  119. $class1 = $this->_em->getClassMetadata(get_class($coll->getOwner()));
  120. $class2 = $coll->getTypeClass();
  121. }
  122. foreach ($mapping['joinTableColumns'] as $joinTableColumn) {
  123. $isRelationToSource = isset($mapping['relationToSourceKeyColumns'][$joinTableColumn]);
  124. if ( ! $isComposite) {
  125. $params[] = $isRelationToSource ? array_pop($identifier1) : array_pop($identifier2);
  126. continue;
  127. }
  128. if ($isRelationToSource) {
  129. $params[] = $identifier1[$class1->getFieldForColumn($mapping['relationToSourceKeyColumns'][$joinTableColumn])];
  130. continue;
  131. }
  132. $params[] = $identifier2[$class2->getFieldForColumn($mapping['relationToTargetKeyColumns'][$joinTableColumn])];
  133. }
  134. return $params;
  135. }
  136. /**
  137. * {@inheritdoc}
  138. *
  139. * @override
  140. */
  141. protected function _getDeleteSQL(PersistentCollection $coll)
  142. {
  143. $columns = array();
  144. $mapping = $coll->getMapping();
  145. $class = $this->_em->getClassMetadata(get_class($coll->getOwner()));
  146. $joinTable = $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform);
  147. foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) {
  148. $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
  149. }
  150. return 'DELETE FROM ' . $joinTable
  151. . ' WHERE ' . implode(' = ? AND ', $columns) . ' = ?';
  152. }
  153. /**
  154. * {@inheritdoc}
  155. *
  156. * @override
  157. * @internal Order of the parameters must be the same as the order of the columns in
  158. * _getDeleteSql.
  159. */
  160. protected function _getDeleteSQLParameters(PersistentCollection $coll)
  161. {
  162. $mapping = $coll->getMapping();
  163. $identifier = $this->_uow->getEntityIdentifier($coll->getOwner());
  164. // Optimization for single column identifier
  165. if (count($mapping['relationToSourceKeyColumns']) === 1) {
  166. return array(reset($identifier));
  167. }
  168. // Composite identifier
  169. $sourceClass = $this->_em->getClassMetadata(get_class($coll->getOwner()));
  170. $params = array();
  171. foreach ($mapping['relationToSourceKeyColumns'] as $columnName => $refColumnName) {
  172. $params[] = isset($sourceClass->fieldNames[$refColumnName])
  173. ? $identifier[$sourceClass->fieldNames[$refColumnName]]
  174. : $identifier[$sourceClass->getFieldForColumn($columnName)];
  175. }
  176. return $params;
  177. }
  178. /**
  179. * {@inheritdoc}
  180. */
  181. public function count(PersistentCollection $coll)
  182. {
  183. $conditions = array();
  184. $params = array();
  185. $mapping = $coll->getMapping();
  186. $association = $mapping;
  187. $class = $this->_em->getClassMetadata($mapping['sourceEntity']);
  188. $id = $this->_em->getUnitOfWork()->getEntityIdentifier($coll->getOwner());
  189. if ( ! $mapping['isOwningSide']) {
  190. $targetEntity = $this->_em->getClassMetadata($mapping['targetEntity']);
  191. $association = $targetEntity->associationMappings[$mapping['mappedBy']];
  192. }
  193. $joinColumns = ( ! $mapping['isOwningSide'])
  194. ? $association['joinTable']['inverseJoinColumns']
  195. : $association['joinTable']['joinColumns'];
  196. foreach ($joinColumns as $joinColumn) {
  197. $columnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform);
  198. $referencedName = $joinColumn['referencedColumnName'];
  199. $conditions[] = $columnName . ' = ?';
  200. $params[] = ($class->containsForeignIdentifier)
  201. ? $id[$class->getFieldForColumn($referencedName)]
  202. : $id[$class->fieldNames[$referencedName]];
  203. }
  204. $joinTableName = $this->quoteStrategy->getJoinTableName($association, $class, $this->platform);
  205. list($joinTargetEntitySQL, $filterSql) = $this->getFilterSql($mapping);
  206. if ($filterSql) {
  207. $conditions[] = $filterSql;
  208. }
  209. $sql = 'SELECT COUNT(*)'
  210. . ' FROM ' . $joinTableName . ' t'
  211. . $joinTargetEntitySQL
  212. . ' WHERE ' . implode(' AND ', $conditions);
  213. return $this->_conn->fetchColumn($sql, $params);
  214. }
  215. /**
  216. * @param PersistentCollection $coll
  217. * @param int $offset
  218. * @param int $length
  219. * @return array
  220. */
  221. public function slice(PersistentCollection $coll, $offset, $length = null)
  222. {
  223. $mapping = $coll->getMapping();
  224. return $this->_em->getUnitOfWork()->getEntityPersister($mapping['targetEntity'])->getManyToManyCollection($mapping, $coll->getOwner(), $offset, $length);
  225. }
  226. /**
  227. * @param PersistentCollection $coll
  228. * @param object $element
  229. * @return boolean
  230. */
  231. public function contains(PersistentCollection $coll, $element)
  232. {
  233. $uow = $this->_em->getUnitOfWork();
  234. // Shortcut for new entities
  235. $entityState = $uow->getEntityState($element, UnitOfWork::STATE_NEW);
  236. if ($entityState === UnitOfWork::STATE_NEW) {
  237. return false;
  238. }
  239. // Entity is scheduled for inclusion
  240. if ($entityState === UnitOfWork::STATE_MANAGED && $uow->isScheduledForInsert($element)) {
  241. return false;
  242. }
  243. list($quotedJoinTable, $whereClauses, $params) = $this->getJoinTableRestrictions($coll, $element, true);
  244. $sql = 'SELECT 1 FROM ' . $quotedJoinTable . ' WHERE ' . implode(' AND ', $whereClauses);
  245. return (bool) $this->_conn->fetchColumn($sql, $params);
  246. }
  247. /**
  248. * @param PersistentCollection $coll
  249. * @param object $element
  250. * @return boolean
  251. */
  252. public function removeElement(PersistentCollection $coll, $element)
  253. {
  254. $uow = $this->_em->getUnitOfWork();
  255. // shortcut for new entities
  256. $entityState = $uow->getEntityState($element, UnitOfWork::STATE_NEW);
  257. if ($entityState === UnitOfWork::STATE_NEW) {
  258. return false;
  259. }
  260. // If Entity is scheduled for inclusion, it is not in this collection.
  261. // We can assure that because it would have return true before on array check
  262. if ($entityState === UnitOfWork::STATE_MANAGED && $uow->isScheduledForInsert($element)) {
  263. return false;
  264. }
  265. list($quotedJoinTable, $whereClauses, $params) = $this->getJoinTableRestrictions($coll, $element, false);
  266. $sql = 'DELETE FROM ' . $quotedJoinTable . ' WHERE ' . implode(' AND ', $whereClauses);
  267. return (bool) $this->_conn->executeUpdate($sql, $params);
  268. }
  269. /**
  270. * @param \Doctrine\ORM\PersistentCollection $coll
  271. * @param object $element
  272. * @param boolean $addFilters Whether the filter SQL should be included or not.
  273. * @return array
  274. */
  275. private function getJoinTableRestrictions(PersistentCollection $coll, $element, $addFilters)
  276. {
  277. $uow = $this->_em->getUnitOfWork();
  278. $mapping = $filterMapping = $coll->getMapping();
  279. if ( ! $mapping['isOwningSide']) {
  280. $sourceClass = $this->_em->getClassMetadata($mapping['targetEntity']);
  281. $targetClass = $this->_em->getClassMetadata($mapping['sourceEntity']);
  282. $sourceId = $uow->getEntityIdentifier($element);
  283. $targetId = $uow->getEntityIdentifier($coll->getOwner());
  284. $mapping = $sourceClass->associationMappings[$mapping['mappedBy']];
  285. } else {
  286. $sourceClass = $this->_em->getClassMetadata($mapping['sourceEntity']);
  287. $targetClass = $this->_em->getClassMetadata($mapping['targetEntity']);
  288. $sourceId = $uow->getEntityIdentifier($coll->getOwner());
  289. $targetId = $uow->getEntityIdentifier($element);
  290. }
  291. $quotedJoinTable = $this->quoteStrategy->getJoinTableName($mapping, $sourceClass, $this->platform);
  292. $whereClauses = array();
  293. $params = array();
  294. foreach ($mapping['joinTableColumns'] as $joinTableColumn) {
  295. $whereClauses[] = $joinTableColumn . ' = ?';
  296. if (isset($mapping['relationToTargetKeyColumns'][$joinTableColumn])) {
  297. $params[] = ($targetClass->containsForeignIdentifier)
  298. ? $targetId[$targetClass->getFieldForColumn($mapping['relationToTargetKeyColumns'][$joinTableColumn])]
  299. : $targetId[$targetClass->fieldNames[$mapping['relationToTargetKeyColumns'][$joinTableColumn]]];
  300. continue;
  301. }
  302. // relationToSourceKeyColumns
  303. $params[] = ($sourceClass->containsForeignIdentifier)
  304. ? $sourceId[$sourceClass->getFieldForColumn($mapping['relationToSourceKeyColumns'][$joinTableColumn])]
  305. : $sourceId[$sourceClass->fieldNames[$mapping['relationToSourceKeyColumns'][$joinTableColumn]]];
  306. }
  307. if ($addFilters) {
  308. list($joinTargetEntitySQL, $filterSql) = $this->getFilterSql($filterMapping);
  309. if ($filterSql) {
  310. $quotedJoinTable .= ' t ' . $joinTargetEntitySQL;
  311. $whereClauses[] = $filterSql;
  312. }
  313. }
  314. return array($quotedJoinTable, $whereClauses, $params);
  315. }
  316. /**
  317. * Generates the filter SQL for a given mapping.
  318. *
  319. * This method is not used for actually grabbing the related entities
  320. * but when the extra-lazy collection methods are called on a filtered
  321. * association. This is why besides the many to many table we also
  322. * have to join in the actual entities table leading to additional
  323. * JOIN.
  324. *
  325. * @param array $mapping Array containing mapping information.
  326. *
  327. * @return string The SQL query part to add to a query.
  328. */
  329. public function getFilterSql($mapping)
  330. {
  331. $targetClass = $this->_em->getClassMetadata($mapping['targetEntity']);
  332. if ($mapping['isOwningSide']) {
  333. $joinColumns = $mapping['relationToTargetKeyColumns'];
  334. } else {
  335. $mapping = $targetClass->associationMappings[$mapping['mappedBy']];
  336. $joinColumns = $mapping['relationToSourceKeyColumns'];
  337. }
  338. $targetClass = $this->_em->getClassMetadata($targetClass->rootEntityName);
  339. // A join is needed if there is filtering on the target entity
  340. $joinTargetEntitySQL = '';
  341. if ($filterSql = $this->generateFilterConditionSQL($targetClass, 'te')) {
  342. $joinTargetEntitySQL = ' JOIN '
  343. . $this->quoteStrategy->getTableName($targetClass, $this->platform) . ' te'
  344. . ' ON';
  345. $joinTargetEntitySQLClauses = array();
  346. foreach ($joinColumns as $joinTableColumn => $targetTableColumn) {
  347. $joinTargetEntitySQLClauses[] = ' t.' . $joinTableColumn . ' = ' . 'te.' . $targetTableColumn;
  348. }
  349. $joinTargetEntitySQL .= implode(' AND ', $joinTargetEntitySQLClauses);
  350. }
  351. return array($joinTargetEntitySQL, $filterSql);
  352. }
  353. /**
  354. * Generates the filter SQL for a given entity and table alias.
  355. *
  356. * @param ClassMetadata $targetEntity Metadata of the target entity.
  357. * @param string $targetTableAlias The table alias of the joined/selected table.
  358. *
  359. * @return string The SQL query part to add to a query.
  360. */
  361. protected function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias)
  362. {
  363. $filterClauses = array();
  364. foreach ($this->_em->getFilters()->getEnabledFilters() as $filter) {
  365. if ($filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias)) {
  366. $filterClauses[] = '(' . $filterExpr . ')';
  367. }
  368. }
  369. $sql = implode(' AND ', $filterClauses);
  370. return $sql ? "(" . $sql . ")" : "";
  371. }
  372. }