Black
Black

Reputation: 5367

doctrine - add joined field to results

In my Symfony (3.0.3) app, I have a table:

 CRM_FORM_RESPONSE(form_response_id int, form_id int, company_id int, response text) 

where I store responses from Companies to small Forms (i.e. questionnaires) Until now I've been retrieving these via Doctrine as follows:

$qb = $doc->getEntityManager ()->createQueryBuilder ();
$query = $qb->select ( 'u' )->from ( 'AppBundle:CrmFormResponse', 'u' )->getQuery();
$result = $query->getResult ();

Now, I'd like to add the name of the Company to the resultset, where the foreign table is:

CRM_COMPANY(comapny_id int, companyname text);

So, my question is about the best-practices for achieving this in Doctrine..

Is there a standard practice in this (common) scenario that avoids these measures?

Upvotes: 1

Views: 1149

Answers (1)

goto
goto

Reputation: 8162

If you are using doctrine, you should speak of objects instead of table: Do you have a mapping which allows you to do CrmFormResponse->getCrmCompany? You should add the mapping of CrmCompany in CrmFormResponse entity this way:

In CrmFormResponse.php

/**
 * @ManyToOne(targetEntity="CrmCompany")
 */
 $crmCompany

Then, the query should be

$query = $qb
      ->select('u')
      ->from ('AppBundle:CrmFormResponse', 'u')
      ->addSelect('company')
      ->innerJoin('u.crmCompany', 'company')
      ->getQuery();

And you get the company name by using

$entityCrmFormResponse->getCompany()->getName()

EDIT: Note than you don't need to change your query to do that, but my query with the join and the addSelect avoid you to do extra queries each time you use $entityCrmFormResponse->getCompany()

Upvotes: 1

Related Questions