I am having a problem with a DQL query to retrieve users and roles from a MySql database. I am using Zend Framework 2 and Doctrine 2.
The query is as follows.
public function getUsers()
{
$builder = $this->getEntityManager()->createQueryBuilder();
$builder->select('u, r')
->from('Application\Entity\Users', 'u')
->leftJoin('Application\Entity\UserRoles', 'r')
->orderBy("u.emailAddress", "ASC");
InfoLogger::vardump($builder->getDQL());
return $builder->getQuery()->getResult(Query::HYDRATE_OBJECT);
}
The above query produces the error, [Syntax Error] line 0, col 91: Error: Expected Literal, got 'BY'
The generated DQL is
SELECT u, r FROM Application\Entity\Users u LEFT JOIN Application\Entity\UserRoles r ORDER BY u.emailAddress ASC
Can someone please spot what is wrong with this query, many thanks.
I have figured it out.
The problem was with the line
->leftJoin('Application\Entity\UserRoles', 'r')
This should have been
->leftJoin('u.userRole', 'r')
userRole is defined in my Entity\Users class.
Related
I have below python method which insert data in to a table. the first column is json_data and the 2nd column is file name. I am getting both the values to this function while calling this method from main.
def insert(sf_handler,data,file_name):
query = """INSERT INTO my_table (DATA,FILE_NAME)
(select (PARSE_JSON('%s'),'%s'))""" % {json.dumps(data),file_name)}
pd.read_sql(query,sf_handler)
But while executing this i am getting below error. Can someone help on this.
TypeError: not enough arguments for format string
I got the answer. Just type cast the file name and remove the flower bracket with parenthesis it will work.
query = """INSERT INTO my_table (DATA,FILE_NAME)
(select (PARSE_JSON('%s'),'%s'))""" % (json.dumps(data),str(file_name))
pd.read_sql(query,sf_handler)
I am trying to JOIN 2 queries in DQL but I am getting an error which says,
[Semantical Error] line 0, col 114 near '(select u.email': Error: Class '(' is not defined.
I have gone through https://stackoverflow.com/questions/24600439/error-in-nested-subquery-in-dql-class-is-not-defined. But I could not figure out. Please help.
My Query is as follows:
$filterQuery = "SELECT tempResult1.email as email,tempResult1.name as name , tempResult1.id as user
FROM (select u.email as email,a.name as name , u.id as user
FROM
Application\Entity\Userhasrole uhr
INNER JOIN
Application\Entity\Oauthrole r with uhr.applicationrole = r.id
INNER JOIN
Application\Entity\Application a with r.application = a.id
INNER JOIN
Application\Entity\Oauthusers u
) tempResult1
LEFT JOIN
(SELECT uhr1.user as user FROM Application\Entity\Userhasrole uhr1 where
a.id = :applicationId
) tempResult2
with tempResult1.user = tempResult2.user";
$queryObject = $this->getEntityManager()
->createQuery($filterQuery);
$queryObject->setParameter('applicationId', $applicationId);
$result = $queryObject->getResult();
You mix 2 concepts of Doctrine2 :
using SQL
using DQL
If you want to achieve that you want, build tables selections, and not entities selections, you should use EntityManager::createNativeQuery() method and set an SQL query as parameter.
EntityManager::createQuery() is used only for DQL queries
I'm trying to order the results of my query by whether or not they match my original entity on a property. I could do this easily in mySQL with the following query:
SELECT * FROM table
ORDER BY prop = 'value' DESC;
However, in Doctrine, when I attempt the following:
// $qb is an instance of query builder
$qb->select('e')
->from('Entity', 'e')
->orderBy('e.prop = :value', 'DESC')
->setParameter('value', 'value');
// grab values
I get a Doctrine syntax error, 'end of string'. I looked into creating a custom function, but that seems like overkill. I'm fairly new to Doctrine, is there a better way to do this?
Since Doctrine ORM 2.2, you can use the HIDDEN keyword and select additional fields, in this case with a CASE expression:
SELECT
e,
CASE WHEN e.prop = :value THEN 1 ELSE 0 END AS HIDDEN sortCondition
FROM
Entity e
ORDER BY
sortCondition DESC
As I struggeled a while to figure out how to create that query using php syntax here's what I came up with:
$value = 'my-value';
$qb->select('e')
->from('Entity', 'e')
->addSelect('CASE WHEN e.prop = :value THEN 1 ELSE 0 END AS HIDDEN sortCondition')
->setParameter('value', $value)
->addOrderBy('sortCondition', 'DESC');
I have problems to create a Doctrine Query with LIKE Expression:
QUERY:
$dql = "SELECT u FROM Users u JOIN u.group g WHERE g.name LIKE lower('ADMIN')";
$query = $em->createQuery($dql);
$result = $query->getResult();
ERROR:
QueryException: [Syntax Error] line 0, col 147: Error: Expected Doctrine\ORM\Query\Lexer::T_STRING, got 'lower'
LOWER was just an example, I need to use other functions in LIKE
EXPRESSION, for example, unnacent...
How can I change Like Expression to support function on both sides?
Example: LOWER(unaccent(u.login)) LIKE LOWER(unaccent('ADMIN'))
The like string needs to have % signs. If you want something that starts with ADMIN then you would write ADMIN% if you want something that ends with ADMIN you would write %ADMIN and finally if you want it to contain ADMIN then it would be %ADMIN%.
Maybe to return a string you can use the CONCAT function of doctrine or you can do it via PHP.
I tested this with QueryBuilder and there doesn't seem to be a solution. The second parameter will not take a function, so I would suggest switching the parameters around:
$dql = "SELECT u FROM Users u JOIN u.group g WHERE UPPER(g.name) LIKE 'ADMIN'";
The db is PostgreSQL. When I try to execute a query with parameters, such as this one
cursor.execute("""
SELECT u.username, up.description,
ts_rank_cd(to_tsvector(coalesce(username,'')|| coalesce(description,'')) , to_tsquery('%s')) as rank
FROM auth_user u INNER JOIN pm_core_userprofile up on u.id = up.user_id
WHERE to_tsvector(coalesce(username,'')|| coalesce(description,'')) ## to_tsquery('%s')
ORDER BY rank DESC;
""", ["hello","hello"])
Django complains of a ProgrammingError, adding syntax error at or near the parameter (in this example, "hello"). Here's the part of the Django generated SQL statement that the error comes from:
to_tsquery('E'hello'')
Even if I copy-paste it to a postgreSQL shell, I get the syntax error. If I omit the 'E' part, it works. What should I make of it?
ozgur,
Try
to_tsquery(%s)
instead of
to_tsquery('%s')
I believe you are missing a ' after the E.