Symfony 2双向关系findBy查询

时间:2014-04-04 18:52:20

标签: symfony doctrine one-to-many query-builder bidirectional-relation

我想使用两个类字段进行双向关系查询,我的类是:

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;

//...
 }

现在我需要进行一个可以通过友好网址过滤信息的查询

例如:

webpage.com/company_friendly_url/branch_friendlyurl

我失去了因为我不知道如何做正确的查询我正在尝试这个,但它现在正在工作。

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

有人知道怎么做吗?

2 个答案:

答案 0 :(得分:0)

试试这段代码:

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

希望这会有所帮助: - )

答案 1 :(得分:0)

使用findBy无法做到这一点,而是需要通过createQueryBuilder创建联接查询

$query = $em->getRepository('AspersoftDirectorioBundle:Company')
       ->createQueryBuilder('c')
       ->join('c.branches', 'b')
       ->where('c.friendlyUrl = :cfriendlyURL')
       ->andWhere('b.friendlyUrl = :bfriendlyURL')
       ->setParameter('cfriendlyURL', $company_friendly_url)
       ->setParameter('bfriendlyURL', $branch_friendly_url)
       ->getQuery();
$results = $query->getResult();