我想使用我的类的两个类字段在双向关系中进行查询:
class Branch {
/**
* @var integer
*
* @ORMColumn(name="id", type="integer")
* @ORMId
* @ORMGeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var Company
*
* @ORMManyToOne(targetEntity="Company", inversedBy="branches")
* @ORMJoinColumn(name="id_company", referencedColumnName="id", nullable=false, unique=false)
*
*/
private $idCompany;
/**
* @var string
*
* @ORMColumn(name="friendly_url", type="string", length=30, nullable=false, unique=true)
*/
private $friendlyUrl;
//...
}
class Company {
/**
* @var integer
*
* @ORMColumn(name="id", type="integer")
* @ORMId
* @ORMGeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var Branch
*
* @ORMOneToMany(targetEntity="Branch", mappedBy="idCompany")
*/
private $branches;
/**
* @var string
*
* @ORMColumn(name="friendly_url", type="string", length=30, nullable=false, unique=true)
*/
private $friendlyUrl;
//...
}
现在我需要执行一个可以通过友好 url 过滤信息的查询
例如:
webpage.com/company_friendly_url/branch_friendlyurl
我输了,因为我不知道如何进行正确的查询,我正在尝试这样做,但它现在正在工作。
$entities = $em->getRepository('AspersoftDirectorioBundle:Company')->findBy(
array(
'friendlyUrl' => $company_friendly_url,
'branches.friendlyUrl' => $branch_friendly_url
)
);
其他人对如何做到这一点有想法吗?
试试这段代码:
$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();
希望这有帮助:-)
不能通过使用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();