2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
39 require_once("data/Relationships/SugarRelationship.php");
42 * Represents a many to many relationship that is table based.
44 class M2MRelationship extends SugarRelationship
46 var $type = "many-to-many";
48 public function __construct($def)
53 $this->name = $def['name'];
55 $lhsModule = $def['lhs_module'];
56 $this->lhsLinkDef = $this->getLinkedDefForModuleByRelationship($lhsModule);
57 $this->lhsLink = $this->lhsLinkDef['name'];
59 $rhsModule = $def['rhs_module'];
60 $this->rhsLinkDef = $this->getLinkedDefForModuleByRelationship($rhsModule);
61 $this->rhsLink = $this->rhsLinkDef['name'];
63 $this->self_referencing = $lhsModule == $rhsModule;
67 * Find the link entry for a particular relationship and module.
72 public function getLinkedDefForModuleByRelationship($module)
74 $results = VardefManager::getLinkFieldForRelationship( $module, BeanFactory::getBeanName($module), $this->name);
75 //Only a single link was found
76 if( isset($results['name']) )
80 //Multiple links with same relationship name
81 else if( is_array($results) )
83 $GLOBALS['log']->error("Warning: Multiple links found for relationship {$this->name} within module {$module}");
84 return $this->getMostAppropriateLinkedDefinition($results);
93 * Find the most 'appropriate' link entry for a relationship/module in which there are multiple link entries with the
94 * same relationship name.
99 protected function getMostAppropriateLinkedDefinition($links)
101 foreach($links as $link)
103 if( isset($link['name']) && $link['name'] == $this->name )
108 //Unable to find an appropriate link, return nothing rather an invalid link.
109 $GLOBALS['log']->error("Unable to determine best appropriate link for relationship {$this->name}");
113 * @param $lhs SugarBean left side bean to add to the relationship.
114 * @param $rhs SugarBean right side bean to add to the relationship.
115 * @param $additionalFields key=>value pairs of fields to save on the relationship
116 * @return boolean true if successful
118 public function add($lhs, $rhs, $additionalFields = array())
120 $lhsLinkName = $this->lhsLink;
121 $rhsLinkName = $this->rhsLink;
123 if (empty($lhs->$lhsLinkName) && !$lhs->load_relationship($lhsLinkName))
125 $lhsClass = get_class($lhs);
126 $GLOBALS['log']->fatal("could not load LHS $lhsLinkName in $lhsClass");
129 if (empty($rhs->$rhsLinkName) && !$rhs->load_relationship($rhsLinkName))
131 $rhsClass = get_class($rhs);
132 $GLOBALS['log']->fatal("could not load RHS $rhsLinkName in $rhsClass");
136 //Many to many has no additional logic, so just add a new row to the table and notify the beans.
137 $dataToInsert = $this->getRowToInsert($lhs, $rhs, $additionalFields);
139 $this->addRow($dataToInsert);
141 if ($this->self_referencing)
142 $this->addSelfReferencing($lhs, $rhs, $additionalFields);
144 if ($lhs->$lhsLinkName->beansAreLoaded())
145 $lhs->$lhsLinkName->addBean($rhs);
146 if ($rhs->$rhsLinkName->beansAreLoaded())
147 $rhs->$rhsLinkName->addBean($lhs);
149 $this->callAfterAdd($lhs, $rhs, $lhsLinkName);
150 $this->callAfterAdd($rhs, $lhs, $rhsLinkName);
153 protected function getRowToInsert($lhs, $rhs, $additionalFields = array())
156 "id" => create_guid(),
157 $this->def['join_key_lhs'] => $lhs->id,
158 $this->def['join_key_rhs'] => $rhs->id,
159 'date_modified' => TimeDate::getInstance()->getNow()->asDb(),
164 if (!empty($this->def['relationship_role_column']) && !empty($this->def['relationship_role_column_value']) && !$this->ignore_role_filter )
166 $row[$this->relationship_role_column] = $this->relationship_role_column_value;
169 if (!empty($this->def['fields']))
171 foreach($this->def['fields'] as $fieldDef)
173 if (!empty($fieldDef['name']) && !isset($row[$fieldDef['name']]) && !empty($fieldDef['default']))
175 $row[$fieldDef['name']] = $fieldDef['default'];
179 if (!empty($additionalFields))
181 $row = array_merge($row, $additionalFields);
188 * Adds the reversed version of this relationship to the table so that it can be accessed from either side equally
191 * @param array $additionalFields
194 protected function addSelfReferencing($lhs, $rhs, $additionalFields = array())
196 if ($rhs->id != $lhs->id)
198 $dataToInsert = $this->getRowToInsert($rhs, $lhs, $additionalFields);
199 $this->addRow($dataToInsert);
203 public function remove($lhs, $rhs)
205 $lhsLinkName = $this->lhsLink;
206 $rhsLinkName = $this->rhsLink;
208 if (!($lhs instanceof SugarBean)) {
209 $GLOBALS['log']->fatal("LHS is not a SugarBean object");
212 if (!($rhs instanceof SugarBean)) {
213 $GLOBALS['log']->fatal("RHS is not a SugarBean object");
216 if (empty($lhs->$lhsLinkName) && !$lhs->load_relationship($lhsLinkName))
218 $GLOBALS['log']->fatal("could not load LHS $lhsLinkName");
221 if (empty($rhs->$rhsLinkName) && !$rhs->load_relationship($rhsLinkName))
223 $GLOBALS['log']->fatal("could not load RHS $rhsLinkName");
227 $dataToRemove = array(
228 $this->def['join_key_lhs'] => $lhs->id,
229 $this->def['join_key_rhs'] => $rhs->id
232 $this->removeRow($dataToRemove);
234 if ($this->self_referencing)
235 $this->removeSelfReferencing($lhs, $rhs);
237 if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
239 if (!empty($lhs->$lhsLinkName))
241 $lhs->$lhsLinkName->load();
242 $this->callAfterDelete($lhs, $rhs, $lhsLinkName);
245 if ($rhs->$rhsLinkName instanceof Link2)
247 $rhs->$rhsLinkName->load();
248 $this->callAfterDelete($rhs, $lhs, $rhsLinkName);
254 * Removes the reversed version of this relationship
257 * @param array $additionalFields
260 protected function removeSelfReferencing($lhs, $rhs, $additionalFields = array())
262 if ($rhs->id != $lhs->id)
264 $dataToRemove = array(
265 $this->def['join_key_lhs'] => $rhs->id,
266 $this->def['join_key_rhs'] => $lhs->id
268 $this->removeRow($dataToRemove);
273 * @param $link Link2 loads the relationship for this link.
276 public function load($link)
278 $db = DBManagerFactory::getInstance();
279 $query = $this->getQuery($link);
280 $result = $db->query($query);
282 $idField = $link->getSide() == REL_LHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
283 while ($row = $db->fetchByAssoc($result))
285 if (empty($row['id']) && empty($row[$idField]))
287 $id = empty($row['id']) ? $row[$idField] : $row['id'];
290 return array("rows" => $rows);
293 public function getQuery($link, $params = array())
295 if ($link->getSide() == REL_LHS) {
296 $knownKey = $this->def['join_key_lhs'];
297 $targetKey = $this->def['join_key_rhs'];
301 $knownKey = $this->def['join_key_rhs'];
302 $targetKey = $this->def['join_key_lhs'];
304 $rel_table = $this->getRelationshipTable();
306 $where = "$rel_table.$knownKey = '{$link->getFocus()->id}'" . $this->getRoleWhere();
308 if (empty($params['return_as_array'])) {
309 return "SELECT $targetKey id FROM $rel_table WHERE $where AND deleted=0";
314 'select' => "SELECT $targetKey id",
315 'from' => "FROM $rel_table",
316 'where' => "WHERE $where AND $rel_table.deleted=0",
321 public function getJoin($link, $params = array(), $return_array = false)
323 $linkIsLHS = $link->getSide() == REL_LHS;
325 $startingTable = (empty($params['left_join_table_alias']) ? $link->getFocus()->table_name : $params['left_join_table_alias']);
327 $startingTable = (empty($params['right_join_table_alias']) ? $link->getFocus()->table_name : $params['right_join_table_alias']);
330 $startingKey = $linkIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
331 $startingJoinKey = $linkIsLHS ? $this->def['join_key_lhs'] : $this->def['join_key_rhs'];
332 $joinTable = $this->getRelationshipTable();
333 $joinTableWithAlias = $joinTable;
334 $joinKey = $linkIsLHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
335 $targetTable = $linkIsLHS ? $this->def['rhs_table'] : $this->def['lhs_table'];
336 $targetTableWithAlias = $targetTable;
337 $targetKey = $linkIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
338 $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
342 //Set up any table aliases required
343 if (!empty($params['join_table_link_alias']))
345 $joinTableWithAlias = $joinTable . " ". $params['join_table_link_alias'];
346 $joinTable = $params['join_table_link_alias'];
348 if ( ! empty($params['join_table_alias']))
350 $targetTableWithAlias = $targetTable . " ". $params['join_table_alias'];
351 $targetTable = $params['join_table_alias'];
354 $join1 = "$startingTable.$startingKey=$joinTable.$startingJoinKey";
355 $join2 = "$targetTable.$targetKey=$joinTable.$joinKey";
359 //First join the relationship table
360 $join .= "$join_type $joinTableWithAlias ON $join1 AND $joinTable.deleted=0\n"
361 //Next add any role filters
362 . $this->getRoleWhere($joinTable) . "\n"
363 //Then finally join the related module's table
364 . "$join_type $targetTableWithAlias ON $join2 AND $targetTable.deleted=0\n";
369 'type' => $this->type,
370 'rel_key' => $joinKey,
371 'join_tables' => array($joinTable, $targetTable),
373 'select' => "$targetTable.id",
376 return $join . $where;
380 * Similar to getQuery or Get join, except this time we are starting from the related table and
381 * searching for items with id's matching the $link->focus->id
383 * @param array $params
384 * @param bool $return_array
385 * @return String|Array
387 public function getSubpanelQuery($link, $params = array(), $return_array = false)
389 $targetIsLHS = $link->getSide() == REL_RHS;
390 $startingTable = $targetIsLHS ? $this->def['lhs_table'] : $this->def['rhs_table'];;
391 $startingKey = $targetIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
392 $startingJoinKey = $targetIsLHS ? $this->def['join_key_lhs'] : $this->def['join_key_rhs'];
393 $joinTable = $this->getRelationshipTable();
394 $joinTableWithAlias = $joinTable;
395 $joinKey = $targetIsLHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
396 $targetKey = $targetIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
397 $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
401 //Set up any table aliases required
402 if (!empty($params['join_table_link_alias']))
404 $joinTableWithAlias = $joinTable . " ". $params['join_table_link_alias'];
405 $joinTable = $params['join_table_link_alias'];
408 $where = "$startingTable.$startingKey=$joinTable.$startingJoinKey AND $joinTable.$joinKey='{$link->getFocus()->$targetKey}'";
410 //Check if we should ignore the role fileter;
411 $ignoreRole = !empty($params['ignore_role']);
413 //First join the relationship table
414 $query .= "$join_type $joinTableWithAlias ON $where AND $joinTable.deleted=0\n"
415 //Next add any role filters
416 . $this->getRoleWhere($joinTable, $ignoreRole) . "\n";
418 if (!empty($params['return_as_array'])) {
419 $return_array = true;
424 'type' => $this->type,
425 'rel_key' => $joinKey,
426 'join_tables' => array($joinTable),
435 protected function getRoleFilterForJoin()
438 if (!empty($this->relationship_role_column) && !$this->ignore_role_filter)
440 $ret .= " AND ".$this->getRelationshipTable().'.'.$this->relationship_role_column;
442 if (empty($this->relationship_role_column_value))
446 $ret.= "='".$this->relationship_role_column_value."'";
458 public function relationship_exists($lhs, $rhs)
460 $query = "SELECT * FROM {$this->getRelationshipTable()} WHERE {$this->join_key_lhs} = {$lhs->id} AND {$this->join_key_rhs} = {$rhs->id}";
462 //Roles can allow for multiple links between two records with different roles
463 $query .= $this->getRoleWhere() . " and deleted = 0";
465 $result = DBManagerFactory::getInstance()->query($query);
466 $row = $this->_db->fetchByAssoc($result);
477 * @return Array - set of fields that uniquely identify an entry in this relationship
479 protected function getAlternateKeyFields()
481 $fields = array($this->join_key_lhs, $this->join_key_rhs);
483 //Roles can allow for multiple links between two records with different roles
484 if (!empty($this->def['relationship_role_column']) && !$this->ignore_role_filter)
486 $fields[] = $this->relationship_role_column;
492 public function getRelationshipTable()
494 if (!empty($this->def['table']))
495 return $this->def['table'];
496 else if(!empty($this->def['join_table']))
497 return $this->def['join_table'];
502 public function getFields()
504 if (!empty($this->def['fields']))
505 return $this->def['fields'];
507 "id" => array('name' => 'id'),
508 'date_modified' => array('name' => 'date_modified'),
509 'modified_user_id' => array('name' => 'modified_user_id'),
510 'created_by' => array('name' => 'created_by'),
511 $this->def['join_key_lhs'] => array('name' => $this->def['join_key_lhs']),
512 $this->def['join_key_rhs'] => array('name' => $this->def['join_key_rhs'])
514 if (!empty($this->def['relationship_role_column']))
516 $fields[$this->def['relationship_role_column']] = array("name" => $this->def['relationship_role_column']);
518 $fields['deleted'] = array('name' => 'deleted');