Retrieves a collection of beans that are related
 to the specified bean and, optionally, returns
 relationship data
 Ajay Singh --> changed as per our equirment.
 "related_fields": #{resolve_related_fields(module_name, related_to)},
427281
def get_relationships(module_name, id, related_to, opts={})
    login! unless logged_in?
    options = { 
      :query => '',
      :fields => [], 
      :link_fields => [],
      :related_fields => [], 
      :deleted => 0
    }.merge! opts  

    json = <<-EOF
      {
        "session": "#{@sugar_session_id}",
        "module_name": "#{module_name}",
        "module_id": "#{id}",
        "link_field_name": "#{related_to.downcase}",
        "related_module_query": "#{options[:query]}",
        "related_fields": #{((options and options[:related_fields].present?) ? options[:related_fields] : resolve_related_fields(module_name, related_to) ).to_json},     
        "related_module_link_name_to_fields_array": #{options[:link_fields].to_json},
        "deleted": #{options[:deleted]}
      }
    EOF
    #puts "#{json}"
    json.gsub!(/^\s{6}/,'')
    SugarCRM::Response.new(send!(:get_relationships, json), @session, {:always_return_array => true}).to_obj
  end
843522
public static List<Field> getClassFields(Class<?> beanClass) {
		Map<String, Field> resultMap = new HashMap<>();
		LinkedList<Field> results = new LinkedList<>();

		Class<?> currentClass = beanClass;
		while (currentClass != null && currentClass != Object.class) {
			for (Field field : currentClass.getDeclaredFields()) {
				if (!field.isSynthetic()) {
					Field v = resultMap.get(field.getName());
					if (v == null) {
						resultMap.put(field.getName(), field);
						results.add(field);
					}
				}
			}
			currentClass = currentClass.getSuperclass();
		}

		return results;
	}
439126
def _has_changed_related(instance):
    
    tracked_related_fields = getattr(
        instance,
        '_tracked_related_fields',
        {}
    ).keys()
    for field, value in instance._original_fields.items():
        if field != 'pk' and \
           not isinstance(instance._meta.get_field(field), ManyToManyField):
            if field in tracked_related_fields:
                if isinstance(instance._meta.get_field(field), ForeignKey):
                    if getattr(instance, '{0}_id'.format(field)) != value:
                        return True
                else:
                    if getattr(instance, field) != value:
                        return True
    return False
929761
private Set<Resource> extractRelationshipField(List<Resource> sourceResources, ResourceField relationshipField, QueryAdapter queryAdapter, Map<ResourceIdentifier, Resource> resourceMap,
			Map<ResourceIdentifier, Object> entityMap, boolean lookUp) {
		Set<Resource> loadedEntities = new HashSet<>();
		for (Resource sourceResource : sourceResources) {
			ResourceIdentifier id = sourceResource.toIdentifier();

			Object source = entityMap.get(id);
			if (source != null && !(source instanceof Resource)) {
				Object targetEntity = PropertyUtils.getProperty(source, relationshipField.getUnderlyingName());

				if (!lookUp && Iterable.class.isAssignableFrom(relationshipField.getType()) && targetEntity == null) {
					throw new InternalServerErrorException(id + " relationship field collection '" + relationshipField.getJsonName() + "' can not be null. Either set the relationship as an empty "
							+ Iterable.class.getCanonicalName() + " or add annotation @" + JsonApiLookupIncludeAutomatically.class.getCanonicalName());
				}
				if (targetEntity == null) {
					continue;
				}
				List<Resource> targetIds = setupRelation(sourceResource, relationshipField, targetEntity, queryAdapter, resourceMap, entityMap);
				loadedEntities.addAll(targetIds);
			}
		}
		return loadedEntities;
	}
316237
def get(self, columns=None):
        
        if columns is None:
            columns = ["*"]

        if self._query.get_query().columns:
            columns = []

        select = self._get_select_columns(columns)

        models = self._query.add_select(*select).get_models()

        self._hydrate_pivot_relation(models)

        if len(models) > 0:
            models = self._query.eager_load_relations(models)

        return self._related.new_collection(models)
811167
def related_to(self):
        
        params = []
        constraints = self.in_constraints
        if self.is_constraint is not None:
            constraints.append(self.is_constraint)

        for constraint in constraints:
            for var in constraint._vars:
                param = var.get_parameter()
                if param not in params and param.uniqueid != self.uniqueid:
                    params.append(param)

        return params
829537
def related_items_changed(self, instance, related_manager):
        
        try:
            count = related_manager.count_queryset()
        except AttributeError:
            count = related_manager.count()
        count_field_name = list(self.fields.keys())[0] % \
                           self.related_field_name
        setattr(instance, count_field_name, count)
        instance.save()
122071
def extract_relationships(cls, fields, resource, resource_instance):
        
        # Avoid circular deps
        from rest_framework_json_api.relations import ResourceRelatedField

        data = OrderedDict()

        # Don't try to extract relationships from a non-existent resource
        if resource_instance is None:
            return

        for field_name, field in six.iteritems(fields):
            # Skip URL field
            if field_name == api_settings.URL_FIELD_NAME:
                continue

            # don't output a key for write only fields
            if fields[field_name].write_only:
                continue

            # Skip fields without relations
            if not isinstance(
                field, (relations.RelatedField, relations.ManyRelatedField, BaseSerializer)
            ):
                continue

            source = field.source
            relation_type = utils.get_related_resource_type(field)

            if isinstance(field, relations.HyperlinkedIdentityField):
                resolved, relation_instance = utils.get_relation_instance(
                    resource_instance, source, field.parent
                )
                if not resolved:
                    continue
                # special case for HyperlinkedIdentityField
                relation_data = list()

                # Don't try to query an empty relation
                relation_queryset = relation_instance \
                    if relation_instance is not None else list()

                for related_object in relation_queryset:
                    relation_data.append(
                        OrderedDict([
                            ('type', relation_type),
                            ('id', encoding.force_text(related_object.pk))
                        ])
                    )

                data.update({field_name: {
                    'links': {
                        "related": resource.get(field_name)},
                    'data': relation_data,
                    'meta': {
                        'count': len(relation_data)
                    }
                }})
                continue

            relation_data = {}
            if isinstance(field, HyperlinkedMixin):
                field_links = field.get_links(resource_instance, field.related_link_lookup_field)
                relation_data.update({'links': field_links} if field_links else dict())
                data.update({field_name: relation_data})

            if isinstance(field, (ResourceRelatedField, )):
                if not isinstance(field, SkipDataMixin):
                    relation_data.update({'data': resource.get(field_name)})

                data.update({field_name: relation_data})
                continue

            if isinstance(
                    field, (relations.PrimaryKeyRelatedField, relations.HyperlinkedRelatedField)
            ):
                resolved, relation = utils.get_relation_instance(
                    resource_instance, '%s_id' % source, field.parent
                )
                if not resolved:
                    continue
                relation_id = relation if resource.get(field_name) else None
                relation_data = {
                    'data': (
                        OrderedDict([
                            ('type', relation_type), ('id', encoding.force_text(relation_id))
                        ])
                        if relation_id is not None else None)
                }

                if (
                    isinstance(field, relations.HyperlinkedRelatedField) and
                    resource.get(field_name)
                ):
                    relation_data.update(
                        {
                            'links': {
                                'related': resource.get(field_name)
                            }
                        }
                    )
                data.update({field_name: relation_data})
                continue

            if isinstance(field, relations.ManyRelatedField):
                resolved, relation_instance = utils.get_relation_instance(
                    resource_instance, source, field.parent
                )
                if not resolved:
                    continue

                relation_data = {}

                if isinstance(resource.get(field_name), Iterable):
                    relation_data.update(
                        {
                            'meta': {'count': len(resource.get(field_name))}
                        }
                    )

                if isinstance(field.child_relation, ResourceRelatedField):
                    # special case for ResourceRelatedField
                    relation_data.update(
                        {'data': resource.get(field_name)}
                    )

                if isinstance(field.child_relation, HyperlinkedMixin):
                    field_links = field.child_relation.get_links(
                        resource_instance,
                        field.child_relation.related_link_lookup_field
                    )
                    relation_data.update(
                        {'links': field_links}
                        if field_links else dict()
                    )

                    data.update({field_name: relation_data})
                    continue

                relation_data = list()
                for nested_resource_instance in relation_instance:
                    nested_resource_instance_type = (
                        relation_type or
                        utils.get_resource_type_from_instance(nested_resource_instance)
                    )

                    relation_data.append(OrderedDict([
                        ('type', nested_resource_instance_type),
                        ('id', encoding.force_text(nested_resource_instance.pk))
                    ]))
                data.update({
                    field_name: {
                        'data': relation_data,
                        'meta': {
                            'count': len(relation_data)
                        }
                    }
                })
                continue

            if isinstance(field, ListSerializer):
                resolved, relation_instance = utils.get_relation_instance(
                    resource_instance, source, field.parent
                )
                if not resolved:
                    continue

                relation_data = list()

                serializer_data = resource.get(field_name)
                resource_instance_queryset = list(relation_instance)
                if isinstance(serializer_data, list):
                    for position in range(len(serializer_data)):
                        nested_resource_instance = resource_instance_queryset[position]
                        nested_resource_instance_type = (
                            relation_type or
                            utils.get_resource_type_from_instance(nested_resource_instance)
                        )

                        relation_data.append(OrderedDict([
                            ('type', nested_resource_instance_type),
                            ('id', encoding.force_text(nested_resource_instance.pk))
                        ]))

                    data.update({field_name: {'data': relation_data}})
                    continue

            if isinstance(field, Serializer):
                relation_instance_id = getattr(resource_instance, source + "_id", None)
                if not relation_instance_id:
                    resolved, relation_instance = utils.get_relation_instance(
                        resource_instance, source, field.parent
                    )
                    if not resolved:
                        continue

                    if relation_instance is not None:
                        relation_instance_id = relation_instance.pk

                data.update({
                    field_name: {
                        'data': (
                            OrderedDict([
                                ('type', relation_type),
                                ('id', encoding.force_text(relation_instance_id))
                            ]) if resource.get(field_name) else None)
                    }
                })
                continue

        return utils._format_object(data)
1244107
def get(self, *args, **kwargs):
        """"""
        self.before_get(args, kwargs)

        relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()

        obj, data = self._data_layer.get_relationship(model_relationship_field,
                                                      related_type_,
                                                      related_id_field,
                                                      kwargs)

        result = {'links': {'self': request.path,
                            'related': self.schema._declared_fields[relationship_field].get_related_url(obj)},
                  'data': data}

        qs = QSManager(request.args, self.schema)
        if qs.include:
            schema = compute_schema(self.schema, dict(), qs, qs.include)

            serialized_obj = schema.dump(obj)
            result['included'] = serialized_obj.data.get('included', dict())

        final_result = self.after_get(result)

        return final_result
687676
def get_relation_fields_from_model(model_class):
    
    relation_fields = []
    all_fields_names = _get_all_field_names(model_class)
    for field_name in all_fields_names:
        field, model, direct, m2m = _get_field_by_name(model_class, field_name)
        # get_all_field_names will return the same field
        # both with and without _id. Ignore the duplicate.
        if field_name[-3:] == '_id' and field_name[:-3] in all_fields_names:
            continue
        if m2m or not direct or _get_remote_field(field):
            field.field_name_override = field_name
            relation_fields += [field]
    return relation_fields
590933
def _get_to_many_relationship_value(self, obj, column):
        
        related_key = column.get('related_key', None)

        related = getattr(obj, column['__col__'].key)
        value = {}
        if related:
            total = len(related)
            for index, rel_obj in enumerate(related):
                if related_key:
                    compiled_res = self._get_formatted_val(
                        rel_obj, related_key, column
                    )
                else:
                    compiled_res = column['__prop__'].compile_obj(
                        rel_obj
                    )
                value['item_%d' % index] = compiled_res
                value[str(index)] = compiled_res
                value["_" + str(index)] = compiled_res

                if index == 0:
                    value['first'] = compiled_res

                if index == total - 1:
                    value['last'] = compiled_res

        return value
1061237
def get_related_model(field):
    """"""
    model = None

    if hasattr(field, 'related_model') and field.related_model:   #  pragma: no cover
        model = field.related_model
    # Django<1.8 doesn't have the related_model API, so we need to use rel,
    # which was removed in Django 2.0
    elif hasattr(field, 'rel') and field.rel:  # pragma: no cover
        model = field.rel.to

    return model
861584
public List<ExtendedRelation> getRelatedTableRelations(String relatedTable)
			throws SQLException {
		return queryForEq(ExtendedRelation.COLUMN_RELATED_TABLE_NAME,
				relatedTable);
	}
355064
def method_missing(method, *args, &block)
      load

      meth = method.to_s

      return get_embedded_resource(meth) if is_embedded?(meth)
      return get_linked_resource(meth) if is_link?(meth)
      return @_changed[meth[0...-1]] = args.first if meth.end_with?('=') and is_field?(meth[0...-1])
      return get_field_value(meth) if is_field?(meth)

      super(method, *args, &block)
    end
562382
def handle_relations(changeset):
    """"""
    for relation in changeset.bundle.get('relations', []):
        relations = [models.Relation(*i.split(':')) if ':' in i
                     else models.Relation(i, '') for i in relation]
        changeset.send({
            'id': 'addRelation-{}'.format(changeset.next_action()),
            'method': 'addRelation',
            'args': [
                '${}'.format(
                    changeset.services_added[rel.name]) +
                (':{}'.format(rel.interface) if rel.interface else '')
                for rel in relations
            ],
            'requires': [changeset.services_added[rel.name] for
                         rel in relations],
        })
    return handle_units
1040729
function getRelationships(model) {
    const modelName = model.constructor.name;
    const properties = typed_conversions_1.hashToArray(exports.relationshipsByModel[modelName], "property") || [];
    let parent = Object.getPrototypeOf(model.constructor);
    while (parent.name) {
        const subClass = new parent();
        const subClassName = subClass.constructor.name;
        properties.push(...typed_conversions_1.hashToArray(exports.relationshipsByModel[subClassName], "property"));
        parent = Object.getPrototypeOf(subClass.constructor);
    }
    return properties;
}
174155
public function getRelatedField($name)
    {
        $field = $this->getField($name);

        return $field instanceof RelatedField ? $field : null;
    }