Symfony Doctrine get entity through another entity - php

I have 3 entities: User, ImaginaryBankAccount and Recharge. One user has one ImaginaryBankAccount and ImaginaryBankAccount can have more than one Recharges. And I want to select from DB all Recharges that belongs to one user.
I have this query:
$resResults = $query->getResult();
$query = $em->createQuery('SELECT rec
FROM AppBundle:Recharge rec
WHERE rec.dateTime > :tresholdDate
AND rec.imaginaryBankAccount.user = :user
ORDER BY rec.dateTime'
)->setParameter('tresholdDate', $dateXDaysBack)
->setParameter('user', $filter->getUser());
$recResults = $query->getResult();
But it throws error:
[Semantical Error] line 0, col 223 near 'user = :user
': Error: Class AppBundle\Entity\Recharge has no field or association named imaginaryBankAccount.user
How can I achieve my goal with Doctrine2?

You have to add a JOIN clause with your imaginaryBankAccount relation like this :
SELECT rec
FROM AppBundle:Recharge rec
JOIN rec.imaginaryBankAccount i
WHERE rec.dateTime > :tresholdDate
AND i.user = :user
ORDER BY rec.dateTime

Related

Join query in Symfony 2

I'm new in Symfony and I have 2 entities (not me who created them):
1st entity: test1 (id,test2_id)
2nd entity: test2 (id,label)
I want to create the query that select from test where test2.label = 1.
$Websites = $this->_em
->createQuery("
SELECT w
FROM \Bundle\Entity\test1 t1
JOIN t1.test2 t2
WHERE t2.label=1")
->getResult();
But I got an error:
Bundle\Entity\test1 has no association named test2
Is there the solution or another way to make it work.
Try this:
$Websites = $this->_em
->createQuery("
SELECT w
FROM \Bundle\Entity\test1 t1
JOIN \Bundle\Entity\test2 t2
WHERE t2.id = t1.test2_id AND t2.label=1")
->getResult();
You can also use createQueryBuilder method
Using createQueryBuilder you can do with the following
$labelValue = 1;
/* Get the EntityManager Resource */
$em = $this->getDoctrine->getManager();
$em->getRepository('AppBundle:test1')
->createQueryBuilder('t1')
->select('t1.w') /*Here you can select respective table columns */
->innerJoin('t1.test2_id', 't2')
->where('t2.label = :label') /* if label value coming from external value else ->where('t2.label = 1') and omit next line */
->setParameter('label',$labelValue) /*In case if your label value coming for external value */
->getQuery()
->getResult();

SQL query joining different tables and count

I am weak with SQL query syntax and i need to make one query with php symfony2.
I have table Company. It have column "city".
I have table CompanyCategory. It have columns "company_id" and "category_id".
I have table Category. It have column "name".
I need to get Total number of categories in all available cities.
Example:
["Riga" => 156,
"Berlin" => 225]
I have looked around for couple of hours but other examples didn't help me enough, because i can't understand such complex queries yet.
I've tried many cases before and now and every time getting different exceptions.
public function getCategoriesInCities() {
return $this->getEntityManager()
->createQuery('SELECT c.city, count(*) as categorycount FROM AdminBundle:Company c INNER JOIN AdminBundle:CompanyCategory s')
->getArrayResult();
}
[Syntax Error] line 0, col -1: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got end of string.
Other case:
public function getCategoriesInCities() {
return $asData = $this->getEntityManager()
->createQuery('SELECT c.city, count(*) as categorycount FROM AdminBundle:Company c INNER JOIN AdminBundle:CompanyCategory s ON(c.id = s.company_id) GROUP BY c.city')
->getArrayResult();
}
[Syntax Error] line 0, col 123: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got 'ON'
Other case:
public function getCategoriesInCities() {
return $this->createQueryBuilder('c')
->select('c.city, COUNT(*) as categorycount')
->innerJoin('AdminBundle:CompanyCategory ON(c.id = cc.company_id)', 'cc')
->groupBy('c.city')
->getQuery()
->getArrayResult();
}
[Syntax Error] line 0, col 138: Error: Expected Literal, got 'BY'
etc.. can't find out how to solve this.
Its a simple JOIN query..
SELECT t.city,count(*) as categoryCount
FROM Company t
INNER JOIN CompanyCategory s ON(t.id = s.company_ID)
GROUP BY t.city
You are not new to this site, so in the future, at least try to show some attempts and efforts that you did on your own.

Using an Inner Join with QueryBuilder on Symfony2

I want to use an inner Join for my tables auto and rent('s'). Its an 1:N relationship. If I use ->innerJoin('s', 'a') it comes to some errors like this:
[Semantical Error] line 0, col 62 near 's a, ChrisKfzBuchungBundle:Auto': Error: Class 's' is not defined.
$repo = $this->getDoctrine()->getRepository('ChrisKfzBuchungBundle:Rent');
$qb = $repo->createQueryBuilder('s');
$qb->from('ChrisKfzBuchungBundle:Auto', 'a')
->where('s.mieteStart >= :date_from')
->andWhere('s.mieteEnde <= :date_to')
->setParameter('date_from', $date_from)
->setParameter('date_to', $date_to);
How do I join one ore more tables with queryBuilder?
There are methods for that and also for me it just worked with a configured relation between the two entites. Here are two working examples:
left join:
$query = $repo->createQueryBuilder('s')
->leftJoin(ChrisKfzBuchungBundle:Auto', 'a', 'WITH', 's.id = a.yourJoinCOlumn')
...
inner join:
$query = $repo->createQueryBuilder('s')
->select('s, a')
->innerJoin('s.yourJoinColumn', 'a')
...

Join 3 table with doctrine 2 query builder

Hey guys i have three table
1) expert_class
2) expert_location
3) expert
i want to fetch data form all three table i know query in mysql i.e
select * from expert_class class
join expert_location loc
on loc.expert_id = class.expert_id
join expert e
on class.expert_id = e.id
where e.is_delete=0
using this query i got all data whatever i want but the problem is i have to write this query using doctrine query bulider i tried like this
$classes = $this->qb
->add('select', 'exp_cls,exp_loc.id as location_id')
->from('Entity\expert_class','exp_cls')
->join('Entity\expert_location', 'exp_loc')
->join('Entity\expert', 'exp')
->where('exp_cls.expert_id = exp.id')
->AndWhere('exp_cls.expert_id = exp_loc.expert_id')
->AndWhere('exp.is_delete = 0')
->getQuery()
->getArrayResult();
when i try to run this query i got this Fatal error
Fatal error: Uncaught exception 'Doctrine\ORM\Query\QueryException' with message 'SELECT exp_cls,exp_loc.id as location_id FROM Entity\expert_class exp_cls INNER JOIN Entity\expert_location exp_loc INNER JOIN Entity\expert exp WHERE exp_cls.expert_id = exp.id AND exp_cls.expert_id = exp_loc.expert_id AND exp.is_delete = 0' in C:\xampp\htdocs\projectname\application\libraries\Doctrine\ORM\Query\QueryException.php:39 Stack trace: #0 C:\xampp\htdocs\projectname\application\libraries\Doctrine\ORM\Query\Parser.php(396): Doctrine\ORM\Query\QueryException::dqlError('SELECT exp_cls,...') #1 C:\xampp\htdocs\projectname\application\libraries\Doctrine\ORM\Query\Parser.php(2363): Doctrine\ORM\Query\Parser->syntaxError('Literal') #2 C:\xampp\htdocs\projectname\application\libraries\Doctrine\ORM\Query\Parser.php(2550): Doctrine\ORM\Query\Parser->Literal() #3 C:\xampp\htdocs\projectname\application\libraries\Doctrine\ORM\Query\Parser.php(2485): Doctrine\ORM\Query\Parser-> in C:\xampp\htdocs\projectname\application\libraries\Doctrine\ORM\Query\QueryException.php on line 44
i also looked up this link Doctrine query builder using inner join with conditions but its not helped
Have you defined relations in your entities? E.g.:
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="expert_location", mappedBy="locations")
*/
private $location;
If you did, then you have to use those connections in your join, e.g.:
->join('exp_cls.locations', 'exp_loc') // This joins the expert_location entity
You you didn't, then you should add an ON condition:
use Doctrine\ORM\Query\Expr\Join;
...
->join('Entity\expert_location', 'exp_loc', Join::ON, $qb->expr()->eq('exp_loc.expert_id', 'exp_cls.expert_id '))

Doctrine query "where notIn" subquery issue

In Symfony2, I have a many:many relationship between users and roles.
I am trying to get a list of all the users which are not linked to the ROLE_SUPER_ADMIN role.
Before migrating to Symfony2/Doctrine, I had achieved this with a simple NOT IN sql query, but for the life of me I can't achieve the same effect with doctrine.
Here is what I am trying:
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$qb2 = $qb;
$dql = $qb->select('sa.id')
->from('AcmeAdminBundle:User', 'sa')
->leftJoin('sa.roles', 'r')
->andWhere('r.role = :role')
->getDQL();
$result = $qb2->select('u')
->from('AcmeAdminBundle:User', 'u')
->where($qb2->expr()->notIn('u.id', $dql))
->setParameter('role', 'ROLE_SUPER_ADMIN')
$users = $result->getQuery()->getResult();
But this is the error:
[Semantical Error] line 0, col 140 near 'sa LEFT JOIN':
Error: 'sa' is already defined.
And this is the output:
SELECT u
FROM AcmeAdminBundle:User sa
LEFT JOIN sa.roles r, AcmeAdminBundle:User u
WHERE u.id NOT IN (
SELECT sa.id
FROM AcmeAdminBundle:User sa
LEFT JOIN sa.roles r
WHERE r.role = :role
)
No idea why it is outputting like that as it should not be performing LEFT JOIN two times, my suspicion is that it has something to do with having two QueryBuilder instances, but could be something else entirely.
You need the MEMBER OF or in your case NOT MEMBER OF option.
$qb->select('sa.id')
->from('AcmeAdminBundle:User', 'sa')
->where(":Role NOT MEMBER OF sa.roles")
->setParameter("Role", <<ROLE_ID_OR_ROLE_ENTITY>>);
I didn't test this code, but it should give you some idea.
Full documentation can be found at http://docs.doctrine-project.org/en/latest/reference/dql-doctrine-query-language.html

Categories