/** * @param string $side * @param string $tableName * @param string $tableAlias * @param array $conditions */ public function join($side, $tableName, $tableAlias, $conditions) { // INNER JOINs take precedence over LEFT JOINs if ($side != 'LEFT' || !isset($this->joins[$tableAlias])) { $this->joins[$tableAlias] = $side; $this->query->join($tableAlias, "{$side} JOIN `{$tableName}` `{$tableAlias}` ON " . implode(' AND ', $conditions)); } }
/** * Joins onto a custom field * * Adds a join to the query to make this field available for use in a clause. * * @param array $customField * @param string $baseTable * @return array * Returns the table and field name for adding this field to a SELECT or WHERE clause */ private function addCustomField($customField, $baseTable = 'a') { $tableName = $customField["table_name"]; $columnName = $customField["column_name"]; $tableAlias = "{$baseTable}_to_{$tableName}"; $this->query->join($tableAlias, "LEFT JOIN `{$tableName}` `{$tableAlias}` ON `{$tableAlias}`.entity_id = `{$baseTable}`.id"); return array($tableAlias, $columnName); }
/** * Populate $this->selectFields * * @throws \Civi\API\Exception\UnauthorizedException */ protected function buildSelectFields() { $return_all_fields = empty($this->select) || !is_array($this->select); $return = $return_all_fields ? $this->entityFieldNames : $this->select; if ($return_all_fields || in_array('custom', $this->select)) { foreach (array_keys($this->apiFieldSpec) as $fieldName) { if (strpos($fieldName, 'custom_') === 0) { $return[] = $fieldName; } } } // Always select the ID. $this->selectFields[self::MAIN_TABLE_ALIAS . ".id"] = "id"; // core return fields foreach ($return as $fieldName) { $field = $this->getField($fieldName); if ($field && in_array($field['name'], $this->entityFieldNames)) { $this->selectFields[self::MAIN_TABLE_ALIAS . ".{$field['name']}"] = $field['name']; } elseif (strpos($fieldName, '.')) { $fkField = $this->addFkField($fieldName, 'LEFT'); if ($fkField) { $this->selectFields[implode('.', $fkField)] = $fieldName; } } elseif ($field && strpos($fieldName, 'custom_') === 0) { list($table_name, $column_name) = $this->addCustomField($field, 'LEFT'); if ($field['data_type'] != 'ContactReference') { // 'ordinary' custom field. We will select the value as custom_XX. $this->selectFields["{$table_name}.{$column_name}"] = $fieldName; } else { // contact reference custom field. The ID will be stored in custom_XX_id. // custom_XX will contain the sort name of the contact. $this->query->join("c_{$fieldName}", "LEFT JOIN civicrm_contact c_{$fieldName} ON c_{$fieldName}.id = `{$table_name}`.`{$column_name}`"); $this->selectFields["{$table_name}.{$column_name}"] = $fieldName . "_id"; // We will call the contact table for the join c_XX. $this->selectFields["c_{$fieldName}.sort_name"] = $fieldName; } } } }