Join 3 table with doctrine 2 query builder - php

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 '))

Related

Symfony Doctrine QueryBuilder add where clause on Join

I have a query builder with the following select:
$starterRepository = $this->getDoctrine()
->getManager()
->getRepository('CatalogBundle:Starter');
$query = $starterRepository->createQueryBuilder('s')
->where('s.active = 1')
->orderBy('s.voltage, s.power, s.serial');
It selects the table "starters", but inside Starter.php I have an association "references" like this:
/**
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="StarterReference", inversedBy="starters")
* #ORM\JoinTable(name="starters_references")
*/
protected $references;
So inside my query results I have both "starters" and "starters_references" tables. 1 starter has many starter references. Now the problem is that I need to select not all of the starter references, but only the ones which has some value in column named "ref_usage".
So I need to write where clause in my query, I am trying this:
->where('reference.ref_usage = 1')
But this way I get only one "starter" item with all the references it has included. And I need all the starter items, but with only the references with ref_usage 1.
Any ideas?
Here is the full files and functions I am using.
Controller function:
http://pastebin.com/0tTEcQbn
Entity "Starter.php":
http://pastebin.com/BFLpKtec
Entity "StarterReference.php":
http://pastebin.com/Kr9pEMEW
EDIT:
This is the query I get if I use:
->where('reference.ref_usage = 1')
SELECT COUNT(*) AS dctrn_count FROM (SELECT DISTINCT id0 FROM (SELECT s0_.id AS id0, s0_.serial AS serial1, s0_.voltage AS voltage2, s0_.power AS power3, s0_.rotation AS rotation4, s0_.teeth AS teeth5, s0_.module AS module6, s0_.b_terminal AS b_terminal7, s0_.comment AS comment8, s0_.commenten AS commenten9, s0_.commentru AS commentru10, s0_.commentpl AS commentpl11, s0_.commentde AS commentde12, s0_.commentes AS commentes13, s0_.type AS type14, s0_.adaptation AS adaptation15, s0_.alternative_product_1 AS alternative_product_116, s0_.alternative_product_2 AS alternative_product_217, s0_.alternative_product_3 AS alternative_product_318, s0_.alternative_product_4 AS alternative_product_419, s0_.active AS active20 FROM starters s0_ INNER JOIN starters_references s2_ ON s0_.id = s2_.starter_id INNER JOIN starter_reference s1_ ON s1_.id = s2_.starterreference_id WHERE s0_.active = 1 AND s1_.ref_usage = 1 ORDER BY s0_.voltage ASC, s0_.power ASC, s0_.serial ASC) dctrn_result) dctrn_table
As you can see it adds ref_usage = 1 to where clause. But the problem is that I don't need it here, I only need to check ref_usage when I inner join my references.
You should join the references in your query and then add the where clause.
$query = $starterRepository->createQueryBuilder('s')
->join('s.references', 'reference')
->where('s.active = 1')
->andwhere('reference.ref_usage = 1')
->orderBy('s.voltage, s.power, s.serial');

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();

Doctrine select multiple objects

I have 2 classes that I want to select from DB using 1 query in Symfony2 Doctrine.
The first entity is Calculation and the second is Polynomial. They have 1:1 relationship:
/**
* Acme\UserBundle\Entity\Calculation
*
* #ORM\Table(name="Calculation")
* #ORM\Entity(repositoryClass="AppBundle\Entity\CalculationRepository")
*/
class Calculation {
//...
/**
* #ORM\OneToOne(targetEntity="Polynomial")
* #ORM\JoinColumn(name="result_polynomial_id", referencedColumnName="id", nullable=false)
**/
private $resultPolynomial;
//...
}
I have a query, that returns me all Calculations of one user:
public function findByUser( $user ) {
return $this->getEntityManager()->createQuery(
'SELECT c
FROM AppBundle:User u
JOIN AppBundle:Polynomial p WITH u = p.user
JOIN AppBundle:Calculation c WITH p = c.resultPolynomial
WHERE u = :user
ORDER BY c.id'
)
->setParameter('user', $user)
->getResult();
}
And to the question... Is there a way to get resultPolynomials of the calculations in one query? If I use something like SELECT c, c.resultPolynomial I get error:
[Semantical Error] line 0, col 12 near 'resultPolynomial
': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
And if I use foreach cycle all calculations to get the their resultPolynomials there are many queries to the DB (1 for each calculation) and it is not good for performance if I have many calculations.
I making a guess because you did not post your User definition nor your Polynomial definition.
I think you can make your DQL this way:
SELECT c, p
FROM AppBundle:User u
JOIN u.polynomial p
JOIN p.calculation c
WHERE u = :user
ORDER BY c.id
I guess you already defined your relations in your model so you don't need to repeat it here.

Symfony & Doctrine getting a joined query to work

I've got an SQL query that returns all the rows in one table (country) which have a related entry in another table (ducks) but I'm struggling to turn this into DQL. This is a standard one-many relationship as each country can have multiple ducks, I believe it is all set up correctly as I can return ducks within a country and return the country a duck is in using standard code.
The working query is:
SELECT c.* FROM country c
INNER JOIN ducks d
ON c.id = d.country_id
GROUP BY c.country
ORDER BY c.country ASC
I've tried converting this to:
SELECT c FROM WfukDuckBundle:Country c
INNER JOIN WfukDuckBundle:Ducks d
ON c.id = d.country_id
GROUP BY c.country
ORDER BY c.country ASC
which produces the following error:
[Semantical Error] line 0, col 79 near 'd ON': Error: Identification Variable
WfukDuckBundle:Ducks used in join path expression but was not defined before.
I'm quite new to Symfony/Doctrine so I suspect it's probably something obvious!
I'm using Symfony 2.0.11 with doctrine
Update:
I've Also tried:
SELECT c FROM WfukDuckBundle:Country c
INNER JOIN c.ducks d
ON c.id = d.country_id
GROUP BY c.country
ORDER BY c.country ASC
where 'ducks' is defined in the Country class as:
/**
* #ORM\OneToMany(targetEntity="Ducks", mappedBy="country")
*/
protected $ducks;
public function __construct()
{
$this->ducks = new ArrayCollection();
}
the definition for country in the ducks class is:
/**
* #ORM\ManyToOne(targetEntity="Country", inversedBy="ducks")
* #ORM\JoinColumn(name="country_id", referencedColumnName="id")
*/
private $country;
Do yourself a favour and use the query builder. Easier to read and update and reuse your queries
<?php
namespace Vendor\Prefix\Repository;
use Doctrine\ORM\EntityRepository;
class SomeRepository extends EntityRepository
{
public function countryDucks()
{
// $em is the entity manager
$qb = $em->createQueryBuilder();
$qb
->select('country', 'duck')
->from('WfukDuckBundle:Country', 'country')
->innerJoin('country.ducks', 'duck')
->groupBy('country.country')
->orderBy('country.country', 'ASC')
;
$query = $qb->getQuery();
// Potential Hydration Modes
// --------------------------------
// Doctrine\ORM\Query::HYDRATE_OBJECT
// Will give you an array of your object entities
// --------------------------------
// Doctrine\ORM\Query::HYDRATE_ARRAY
// Will give you an array mimicking
// your object graph
// --------------------------------
return $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
}
}

Error while joining tables with Zend_Db

Why am I getting this:
An error occurred
Application error
Exception information:
Message: Select query cannot join with another table
while trying to join two tables?
I have this line code inside my model which extends Zend_Db_Table_Abstract
public function getProjects() {
$select = $this->select()
->from(array('sub' => $this))
->join(array('main' => 'main_projects'), 'main.mai_id = sub.mai_id');
return $this->fetchAll($select);
}
And I use this in my controller: $this->view->entries = $this->sub_projects->getProjects();
Why the hell I get this error? I just want to make a simple join
SELECT sub.*, main.mai_title FROM sub_projects AS sub INNER JOIN main_projects AS main ON sub.mai_id = projects.mai_id;
enter code here
I think here is your solution and explanation : http://www.mail-archive.com/fw-general#lists.zend.com/msg24553.html
Another solution here : Translating a query to use Zend_Db_Select

Categories