Search code examples
symfonydoctrineone-to-manyquery-builderbidirectional-relation

Symfony2 Biderectional Relationship finBy query


I want to do a query in a bidirectional relationship using both class fields my classes are:

class Branch {

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;

/**
 * @var Company
 * 
 * @ORM\ManyToOne(targetEntity="Company", inversedBy="branches")
 * @ORM\JoinColumn(name="id_company", referencedColumnName="id", nullable=false, unique=false)
 * 
 */
private $idCompany;

/**
 * @var string
 *
 * @ORM\Column(name="friendly_url", type="string", length=30, nullable=false, unique=true)
 */
private $friendlyUrl;

//...

}


class Company {

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")  
 */
private $id;


/**
 * @var Branch
 * 
 * @ORM\OneToMany(targetEntity="Branch", mappedBy="idCompany")
 */
private $branches;

/**
 * @var string
 *
 * @ORM\Column(name="friendly_url", type="string", length=30, nullable=false, unique=true)
 */
private $friendlyUrl;

//...
 }

Now I need to do a query thats can filter the information by friendly urls

for example:

webpage.com/company_friendly_url/branch_friendlyurl

Im lossing because I dont know how to do the correct query Im trying with this, but it is now working.

$entities = $em->getRepository('AspersoftDirectorioBundle:Company')->findBy(
   array(
      'friendlyUrl' => $company_friendly_url, 
      'branches.friendlyUrl' => $branch_friendly_url
   )
);

somebody else have idea on how to do it?


Solution

  • try this code:

    $companies = $em->createQuery("SELECT c, b from AspersoftDirectorioBundle:Company c LEFT JOIN c.branches b with b.friendlyUrl = :branchFriendlyUrl where c.friendlyUrl = :companyFriendlyUrl")
                    ->setParameter("branchFriendlyUrl", $branch_friendly_url)
                    ->setParameter("companyFriendlyUrl", $company_friendly_url)
                    ->getResult();
    

    hope this helps :-)