Doctrine: Invalid parameter number: number of bound variables does not match number of tokens - dql

I have a Subscribers table which consists of emails (not unique) and a category for each email.
I am trying to find the emails for each category using the following function but get the error:
Invalid parameter number: number of bound variables does not match number of tokens
This is my function:
public function findEmailsByCategory($category)
{
$result = $this->getEntityManager()
->createQuery(
'SELECT s.email FROM NEWSBlogBundle:Subscribers s WHERE s.category =:category'
)->getResult();
return $result;
}
Can anyone tell me where I'm going wrong?

You didn't specified "category" parameter value. Please see Doctrine DQL usage.
ex.
$query = $em->createQuery('SELECT u FROM ForumUser u WHERE u.username = :name');
$query->setParameter('name', 'Bob'); // you didn't add required parameter.
$users = $query->getResult();

Related

Create a select distinct request with symfony 5

In symfony 5, with doctrine I want to create a request to select distinct type.
So, I have made the following code:
/**
* #Route("/hometest", name="hometest")
*/
public function index2()
{
$lesservices = $this->getDoctrine()->getRepository(Services::class)->findAll();
$em = $this->getdoctrine()->getManager();
$query = $em->createQuery('SELECT distinct serv.souscategorie FROM App\Entity\Services serv');
$services = $query->getResult();
return $this->render('home/indextest.html.twig', array ('servicesliste' => $lesservices, 'distinctscat' => $query));
}
But, I am getting this error :
[Semantical Error] line 0, col 21 near 'souscategorie': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
In fact, souscategorie is a relation field and if I put a string field at his place everything goes right.
Do I have to make a join request to have my souscategorie results ?
Thanks for your answers.
You are selecting a relation field, this might be your problem.
By searching your error i found out this answer which could help you solve your query without having to join:
SELECT DISTINCT IDENTITY(serv.souscategorie) ...

Symfony / Doctrine findBy

Hove to create custom Repository function who query by json field. I have params column in my database who look like this:
"params": {
"product": "stopper",
"itemIdentifier": ""
}
I want to query record by product value. In this case stopper term.
You can achieve this with a classic example :
In your repository :
For one result
public function findOneProduct($value): ?Params
{
return $this->createQueryBuilder('p')
->andWhere('p.product = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
For multiple result
public function findParamsByProduct($value): ?Params
{
return $this->createQueryBuilder('p')
->andWhere('p.product = :val')
->setParameter('val', $value)
->orderBy(/*some field */)
->setMaxResults(/*if needed*/)
->getQuery()
->getResults()
;
}
In your controller:
$stoppers = $entityManager->getRepository(Params::class)->findParamsByProduct('stopper');
If I understood your question correctly, you have a table with a column named params. And inside this mysql column, you store JSON text.
And then you want to query that table and filter by looking into the JSON in your column.
This can be a bit tedious and was also highly discouraged in the past (prior to the JSON Type in Mysql 5.7.8).
Best practices would be to have a NoSQL DB such as MongoDB which is actual JSON stored in a collection(table).
Anyways, there is a solution for you.
Taking into account #AppyGG explained how to make a custom repository function.
First of all, we have to make a query using pure SQL.
It can be done two ways:
1.Return arrays containing your data.
$conn = $this->getEntityManager()->getConnection();
$sql = '
SELECT * FROM product p
WHERE p.price > :price
ORDER BY p.price ASC
';
$stmt = $conn->prepare($sql);
$stmt->execute(['price' => $price]);
// returns an array of arrays (i.e. a raw data set)
return $stmt->fetchAll();
2.Return hydrated Entities
use Doctrine\ORM\Query\ResultSetMappingBuilder;
$rsm = new ResultSetMappingBuilder($entityManager);
$rsm->addRootEntityFromClassMetadata('MyProject\Product', 'p');
$sql = '
SELECT * FROM product p
WHERE p.price > :price
ORDER BY p.price ASC
';
$nql = $this->_em->createNativeQuery( $sql, $rsm );
$nql->setParameter('price', $price);
//Return loaded entities
return $nql->getResult();
Now, knowing how to make make a MySQL query with doctrine, we want to select results filtered in JSON data.
I'm am referencing this beautiful stackoverflow which explains it all:
How to search JSON data in MySQL?
The easiest solution proposed in there requires at least MySQL 5.7.8
Your MySQL query would be as follow:
//With $entity->getParams() == '{"params": {"product":"stopper", "itemIdentifier":""}}'
$conn = $this->getEntityManager()->getConnection();
$sql = '
SELECT * FROM Entity e
WHERE JSON_EXTRACT(e.params, "$.params.product") = :product
';
//Or Like this if the column is of Type JSON in MySQL(Not doctrine, yes check MySQL).
$sql = '
SELECT * FROM Entity e
WHERE e.params->"$.params.product" = :product
';
$stmt = $conn->prepare($sql);
$statement->bindValue("product","stopper");
$stmt->execute();
return $statement->fetchAll();
Hope this helps!
P.S: Note that my example uses a column named 'params' with a Json containing also a named attribute 'params', this can be confusing. The intended purpose is to show how to do multiple level filtering.

How to get previous and next entity through entity manager

This is how i'm able to fetch an user entity using it's id:
$userEntity = $em->getRepository('ModelBundle:User')->find($userId);
Is there a way to get previous and next entity based on this $userEntity?
For example: i fetched $userEntity and it's id is 100, now i want fetch previous entity irrespective to its id 99, 80, 70 whatever it is! same with case with next entity..
I can already fetch next and previous using some PHP hack, however i'm looking for better approach..
Edited:
Just to clarify i'm looking for object oriented approach, something like below:
$userEntity = $em->getRepository('ModelBundle:User')->find($userId);
$previousUserEntity = $userEntity->previous(); //example
$previousUserEntity = $userEntity->next(); //example
I know userEntity does't contain any method like previous() and next(), it's just an example, if anything like that exist which can help directly get next and previous entities in object oriented fashion!
Add this funstion to your repository class
public function previous(User $user)
{
return $this->getEntityManager()
->createQuery(
'SELECT u
FROM ModelBundle:User u
WHERE u.id = (SELECT MAX(us.id) FROM ModelBundle:User us WHERE us.id < :id )'
)
->setParameter(':id', $user->getId())
->getOneOrNullResult();
}
public function next(User $user)
{
return $this->getEntityManager()
->createQuery(
'SELECT u
FROM ModelBundle:User u
WHERE u.id = (SELECT MIN(us.id) FROM ModelBundle:User us WHERE us.id > :id )'
)
->setParameter(':id', $user->getId())
->getOneOrNullResult();
}
It's possible to get the previous and next records by searching for all the records with a value greater or less than a given value, sort them and then take only the first or last result.
Let's say we have these ids:
70
80
99
100
In order to get the user before 99, we want the last user which id is less than 99. Here is the code for adding this in a custom repository:
public function getPreviousUser($userId)
{
$qb = $this->createQueryBuilder('u')
->select('u')
// Filter users.
->where('u.id < :userId')
->setParameter(':userId', $userId)
// Order by id.
->orderBy('u.id', 'DESC')
// Get the first record.
->setFirstResult(0)
->setMaxResults(1)
;
$result = $qb->getQuery()->getOneOrNullResult();
}
And in the controller:
$em->getRepository('ModelBundle:User')->getPreviousUser($userId);
This will return the record with id 80.
In order to get the user after 99, we want the first user which id is greater than 99:
public function getNextUser($userId)
{
$qb = $this->createQueryBuilder('u')
->select('u')
->where('u.id > :userId')
->setParameter(':userId', $userId)
->orderBy('u.id', 'ASC')
->setFirstResult(0)
->setMaxResults(1)
;
$result = $qb->getQuery()->getOneOrNullResult();
}
And in the controller:
$em->getRepository('ModelBundle:User')->getNextUser($userId);
This will return the record with id 100.

Delete function using join in DQL

I'm trying to use the Doctrine QueryBuilder to perform the Delete function using query
I need to delete a record that is present in 2 tables ,
in TcTracks table the id is "id" and in TcWall teh id is "related_id"
my controller
public function deleteAction(Request $request){
$deleteQuery = $this->getDoctrine()
->getManager()
->createQueryBuilder('d')
->delete('TcPlayerBundle:TcTracks', 'd')
->innerJoin('TcprofileBundle:TcWall', 't', 'ON', 'd.id = t.related_id')
->where('d.id = :dId')
->setParameter('wId', $request->get('related_id'))
->setParameter('dId', $request->get('id'))
->getQuery();
$deleted = $deleteQuery->getResult();
$deleted->flush();
return $this->render('TcPlayerBundle:Default:all.html.twig',array(
'tracks' => $tracks
));
}
i need to delete same record in two tables , but its not performing for both tables, kindly help me
i'm getting error as
Invalid parameter number: number of bound variables does not match number of tokens
Remove the line below:
->setParameter('wId', $request->get('related_id'))
There is only :dId but no :wId.
Actually you did inner join by 'd.id = t.related_id', so related_id is not necessary to set any more.
You don't have wID parameter anywhere in query. In the same time you're using ->setParameter('wId', $request->get('related_id')) which is obsolete in this case. Try to remove this row and it should be fine.
Is one-to-many realation with your entities
TcPlayerBundle:TcTracks
and
TcprofileBundle:TcWall
if like that,you can do some like:
oneToMany:
cascade: [remove]
in your config 'yourentity.orm.yml' file..
hope hlep you!

Get total number of rows by using 'SQL_CALC_FOUND_ROWS' and Doctrine NativeQuery

I have a simple query which selects entities and uses limit statement. I am using Doctrine NativeQuery because I have FIELD() function in sql query, and I need a collection of objects as a result.
That query works.
However I need also a total number of records, so I use SQL_CALC_FOUND_ROWS in the first query. After the first gets the result I create another ResultSetMapping, another $nativeQuery, execute SELECT FOUND_ROWS() AS found_rows and I keep getting total number of '1'.
$rsm = new ResultSetMapping();
$rsm->addEntityResult('\\MyCompany\\Administration\\Domain\\Model\\Applicant\\Applicant', 'a');
$rsm->addFieldResult('a', 'first_name', 'firstName');
$rsm->addFieldResult('a', 'last_name', 'lastName');
$query = $this->em->createNativeQuery('SELECT SQL_CALC_FOUND_ROWS * FROM recruitment_applicant ORDER BY FIELD(id,5,15,8,17,2,1,16,9,7,11,6,10,12,13,14,18)', $rsm);
$result = $query->getResult(); // this result is ok
$sqlCountRows = "SELECT FOUND_ROWS() AS found_rows";
$countRowsRsm = new ResultSetMapping();
$countRowsRsm->addScalarResult('found_rows', 'foundRows');
$countRowsQuery = $this->em->createNativeQuery($sqlCountRows,$countRowsRsm);
$rowsCount = $countRowsQuery->getResult();
$total = $rowsCount[0]['foundRows']; // result is '1' when it should be '16'
I used this example.
You don't have to use native query. FIELD() is really very easy to implement as a custom DQL function:
Read DQL User Defined Functions and How to Register Custom DQL Functions on Doctrine/Symfony documentation.
FIELD() implementation:
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
class Field extends FunctionNode
{
private $field = null;
private $values = array();
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->field = $parser->arithmeticPrimary();
while (count($this->values) < 1 || $parser->getLexer()->lookahead['type'] !== Lexer::T_CLOSE_PARENTHESIS) {
$parser->match(Lexer::T_COMMA);
$this->values[] = $parser->arithmeticPrimary();
}
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(SqlWalker $sqlWalker)
{
$values = array();
foreach ($this->values as $value) {
$values[] = $value->dispatch($sqlWalker);
}
return sprintf('FIELD(%s, %s)', $this->field->dispatch($sqlWalker), implode(', ', $values));
}
}
You won't event need a count query. However, if you'd need COUNT(*) query you can easily clone your original query and use CountWalker to create count query from select query.
I found out what might be a cause of the problem: Symfony2 profiler, queries section, shows total of 22 queries executed. My first query gets run third in a row and my second query, the one to return the number of rows gets executed 13th.
SQL_CALC_FOUND_ROWS works if SELECT FOUND_ROWS() is run immediately after the first query.

Resources