I have a custom dql match function and would like to select the match result as 'score' before ordering by that score. How can I adjust the following query to achieve this?
$qb = $this->getEntityManager()->createQueryBuilder();
$qb
->select('i', 'bi')
->from('AdminBundle:Items', 'i')
->where('i.instock=1')
->leftJoin('AdminBundle:MyTable','bi',\Doctrine\ORM\Query\Expr\Join::WITH, 'i.id = bi.productId')
->andWhere('bi.productId IS NULL')
->andWhere('MATCH (i.brand, i.store, i.title, i.description, i.keywords) AGAINST (:search BOOLEAN) > 0')
->andWhere('i.instock = 1')
->setParameter('search', $searchString)
->setMaxResults( $limit )
;
$results = $qb->getQuery()->getArrayResult();
I do not know if I understand your question, do you want to add to your select what you have in your where (match...) and order by it?
You can add not-mapped selects like this:
$qb->addSelect('MY_FUNCTION(my.params) AS HIDDEN mySelectAlias')
In your case, sth like:
$qb->addSelect('(MATCH (i.brand, i.store, i.title, i.description, i.keywords) AGAINST (:search BOOLEAN)) AS HIDDEN mySelectAlias')
And in your order by:
$qb->orderBy('mySelectAlias', 'desc');
Complete example:
https://coderwall.com/p/o5snag
Related
In fact, after returning a result of data from the database using Doctrine,
I'm trying to add the row count number, without calling another query request.
This is my function:
public function search(QueryBuilder $qb, string $search)
{
$qb = $qb->addSelect('COUNT(n) as count');
$search = $this->escape($search);
$qb->andWhere(
$qb->expr()->like('n.title', $qb->expr()->literal('%'.$search.'%'))
);
$qb->setMaxResults(2);
}
This is my DQL:
SELECT n, COUNT(n) as count FROM CoreBundle\Entity\News n LEFT JOIN n.category c WHERE n.title LIKE '%re%'
And I need to return as a result a all my data with a count key that refer to the number of rows.
The problem that I'm getting only the first row with id = 1, and it seems that the count number is correct.
So the result should by something like that:
['count' => 2 , [Newsn1,Newsn2]
Don't tell me to use array_count because I need to get the count of rows in the database, and I have a setMaxResults function, so I will not get a real number of rows.
I don't know the configuration of your table, I just can imagine. So, here's my try:
For getting counts for all titles in your table:
# SQL
SELECT COUNT(id) AS count, GROUP_CONCAT(title SEPARATOR ', ') AS titles FROM newses GROUP BY title
# DQL. assuming you are using a Repository method:
$qb = $this->createQueryBuilder('n');
$qb
->select("COUNT(n.id) AS count, GROUP_CONCAT(n.title SEPARATOR ', ') AS titles")
->leftJoin('n.category', 'c')
->groupBy('n.title')
;
return $qb->getQuery()->getArrayResult();
For getting counts for a particular title:
# SQL
SELECT COUNT(id) AS count, GROUP_CONCAT(title SEPARATOR ', ') AS titles FROM newses WHERE n.title LIKE '%news%' GROUP BY title
# NewsRepository.php
public function getTitlesCount($title)
{
$qb = $this->createQueryBuilder('n');
$qb
->select("COUNT(n.id) AS count, GROUP_CONCAT(n.title SEPARATOR ', ') AS titles")
->leftJoin('n.category', 'c')
->where('n.title LIKE :title')
->setParameter('title', "%{$title}%")
->groupBy('n.title')
;
return $qb->getQuery()->getArrayResult();
}
This code:
$builder->select('p')
->from('ProProposalBundle:Proposal', 'p')
->leftJoin('ProProposalBundle:Proposal:Vote', 'v')
->leftJoin('ProUserBundle:User', 'u')
->andWhere('v.proposal = p')
->andWhere('v.user = u')
->andWhere('v.decision = "in_favor" OR v.decision = "against"')
->andWhere('u = :user')
->setParameter('user', $options['user'])
->andWhere('p.community = :community')
->setParameter('community', $community)
->andWhere('p.archived = :archived')
->setParameter('archived', $options['archived'])
->leftJoin('p.convocation', 'c')
->andWhere("p.convocation IS NULL OR c.status = '" . Convocation::STATUS_PENDING . "'");
return $builder->getQuery()->execute();
is returning an error:
[Syntax Error] line 0, col 106: Error: Expected Literal, got 'JOIN'
This is the formed query:
SELECT p FROM ProProposalBundle:Proposal p LEFT JOIN ProProposalBundle:Proposal:Vote v LEFT JOIN ProUserBundle:User u LEFT JOIN p.convocation c WHERE v.proposal = p AND v.user = u AND (v.decision = "in_favor" OR v.decision = "against") AND u = :user AND p.community = :community AND (p.convocation IS NULL OR c.status = 'pending') ORDER BY p.created desc
LEFT JOIN is missing the ON or WITH condition. The question is: what am I doing wrong with DQL query? Am I wrong with leftJoin() method?
Doctrine ORM needs you to tell which relation is joined, not the entity itself (you did it well with p.convocation) :
$builder->select('p')
->from('ProProposalBundle:Proposal', 'p')
->leftJoin('ProProposalBundle:Proposal\Vote', 'v', 'WITH', 'v.proposal = p AND v.user = :user AND (v.decision = :in_favor OR v.decision = :against)')
->setParameter('user', $options['user'])
->setParameter('in_favor', 'in_favor')
->setParameter('against', 'against')
->andWhere('p.community = :community')
->setParameter('community', $community)
->andWhere('p.archived = :archived')
->setParameter('archived', $options['archived'])
->leftJoin('p.convocation', 'c')
->andWhere("p.convocation IS NULL OR c.status = :pending")
->setParameter('pending', Convocation::STATUS_PENDING);
return $builder->getQuery()->execute();
edit: I inversed Vote relation as you commented and removed useless WHERE clauses (Doctrine automatically resolves JOIN ON clause. I also transferred some WHERE clauses about joins in the optional params (WITH in DQL).
edit2: Without relation between Proposal and Vote, not sure it works.
edit3: Best practice is to use setParameter for all values in WHERE clauses.
I'm using Symfony/Doctrine.
I'm trying to select last 4 rows from table, but im getting error.
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery(
'SELECT c FROM DprocMainBundle:Courses c ORDER BY id DESC LIMIT 4'
);
$course = $query->getResult();
This is my query but it shows error.
Expected end of string, got 'LIMIT'
How should i use limit, and get the LAST 4 rows?
thanks!
Use setMaxResults() to limit the number of results.
$course = $query->setMaxResults(4)->getResult();
If you want to use this for pagination you can add a setFirstResult() call.
$course = $query->setMaxResults(4)->setFirstResult(10)->getResult();
I basically want to do this SQL statement:
SELECT * FROM Table1
JOIN Table2
ON (
Table2.ID = Table1.THIS_ID
OR
Table2.ID = Table1.THAT_ID
)
Using createQueryBuilder and NOT createQuery.
Is it possible?
All the examples I can find only deal with a single condition and don't tackle the issue of AND/OR within a join.
Thanks.
You can try something like that (in a repository for instance):
$qb = $this->createQueryBuilder('t1');
$qb->join('t1.table2', 't2', Expr\Join::WITH, 't2.id = t1.thisId OR t2.id = t1.thatId');
...
You can do it like this:
$qb->leftJoin(
'u.Phonenumbers',
'p',
Expr\Join::WITH,
$qb->expr()->orx(
$qb->expr()->eq('t.this_id', 't1.id'),
$qb->expr()->eq('t.this_id', 't1.id')
)
)
Ok i have this code:
SELECT
IFNULL(s2.id,s1.id) AS effectiveID,
IFNULL(s2.status, s1.status) AS effectiveStatus,
IFNULL(s2.user_id, s1.user_id) as effectiveUser,
IFNULL(s2.likes_count, s1.likes_count) as effectiveLikesCount
FROM statuses AS s1
LEFT JOIN statuses AS s2 ON s2.id = s1.shared_from_id
WHERE s1.user_id = 4310
ORDER BY effectiveID DESC
LIMIT 15
And i need to rewrite it to querybuilder. Something like that?
$fields = array('IFNULL(s2.id,s1.id) AS effectiveID','IFNULL(s2.status, s1.status) AS effectiveStatus', 'IFNULL(s2.user_id, s1.user_id) as effectiveUser','IFNULL(s2.likes_count, s1.likes_count) as effectiveLikesCount');
$qb=$this->_em->createQueryBuilder()
->select($fields)
->from('WallBundle:Status','s1')
->addSelect('u')
->where('s1.user = :user')
->andWhere('s1.admin_status = false')
->andWhere('s1.typ_statusu != :group')
->setParameter('user', $user)
->setParameter('group', 'group')
->leftJoin('WallBundle:Status','s2', 'WITH', 's2.id=s1.shared_from_id')
->innerJoin('s1.user', 'u')
->orderBy('s1.time', 'DESC')
->setMaxResults(15);
var_dump($query=$qb->getQuery()->getResult());die();
This error is
[Syntax Error] line 0, col 7: Error: Expected known function, got 'IFNULL'
Use COALESCE instead of IFNULL like this
$fields = array('COALESCE(s2.id,s1.id) AS effectiveID','COALESCE(s2.status, s1.status) AS effectiveStatus', 'COALESCE(s2.user_id, s1.user_id) as effectiveUser','COALESCE(s2.likes_count, s1.likes_count) as effectiveLikesCount');
COALESCE return the first value not null in the list, so if A is null and B not null, then COALESCE(A,B) will return B.
There is a Doctrine extension that adds this among others.
This is the DQL file from IFNULL.
https://github.com/beberlei/DoctrineExtensions/blob/master/src/Query/Mysql/IfNull.php
This chapter explains how you use them.
http://symfony.com/doc/2.0/cookbook/doctrine/custom_dql_functions.html