[SalesForce] no viable alternative at character ‘\’

When I run the below code, I get this error:

no viable alternative at character '\'

Code:

public void getChildRecords() {
    DescribeSObjectResult describe = objectVar.getSObjectType().getDescribe();

    childRelationshipNames = new List<String>();

    for (Schema.ChildRelationship child:describe.getChildRelationships()) {
        childRelationshipNames.add(child.getRelationshipName());
    }

    String relationshipQuery = 'SELECT ';

    for (String relationship:childRelationshipNames) {
        if (relationship != 'null' && relationship != null) { 
            relationshipQuery += '(SELECT Id, FirstName, LastName, Email, Salary__c FROM ' + relationship + '), ';
        }
    }

    relationshipQuery += 'Id,  FirstName, LastName, Email, Salary__c FROM ' + describe.getName() + ' WHERE ID = \'' + objectVar.Id + \'' ';

    objectVar = Database.query(relationshipQuery);
}

Best Answer

As noted in the comments, you've escaped the wrong single quote.

Incorrect

'WHERE Id = \'' + someId + \'' '

Correct

'WHERE Id = \'' + someId + '\''

Also noted in the comments, you can use bind variables if you cache the Id itself as a top level property.

Id someId = objectVar.Id;
objectVar = Database.query('SELECT ... FROM ... WHERE Id = :someId');