我有这样的东西:
$languages = ["English", "German", "Spanish"];
作业实体:
/**
* @FlowEntity
*/
class Job {
/**
* The name of first language for the job (M:1 unidirectional)
*
* @var PATHLanguage
* @ORMManyToOne
*/
protected $language1;
/**
* The name of second language for the job (M:1 unidirectional)
*
* @var PATHLanguage
* @ORMManyToOne
*/
protected $language2;
}
和语言实体:
/**
* @FlowEntity
*/
class Language
{
/**
* The language name
*
* @var string
* @FlowIdentity
* @FlowValidate(type="Text")
* @FlowValidate(type="NotEmpty")
* @FlowValidate(type="StringLength", options={ "minimum"=1, "maximum"=80})
* @ORMColumn(length=80)
*/
protected $name;
}
如何在$languages中获得所有具有语言1或语言2的工作? 我尝试了以下方法,但它不起作用...
我得到空的结果。
$queryBuilder
->resetDQLParts()
->select("job")
->from("Job", "job")
->andWhere(
$queryBuilder->expr()->orX(
$queryBuilder
->innerJoin('job.language1', 'language1')
->andWhere($queryBuilder->expr()->in("language1.name", $languages)),
$queryBuilder
->innerJoin('job.language2', 'language2')
->andWhere($queryBuilder->expr()->in("language2.name", $languages))
)
);
有什么想法吗?
我不完全理解你写的查询,这肯定不是我过去使用QueryBuilder的方式。我已经重写了如何使用它。
语言字段没有说明它们引用的实体应该是:
/** @ORMManyToOne(targetEntity='AppBundleEntityLanguage')
假设表结构为:
ID | Job Name | Language1 | Language2
1 | Job1 | French | English
2 | Job2 | English | Spanish
该 SQL 将是:
SELECT * FROM `jobs`
WHERE `language1` IN ("English", "French")
OR `language2` IN ("English", "French");
翻译过来就是:
$this->createQueryBuilder('job')
->where('job.language1 IN (:languages)')
->orWhere('job.language2 IN (:languages)')
->setParameter("languages", $languages)
->getQuery()
->getResult();
但是,表结构为:
-- Jobs
ID | Job Name | Language1 | Language2
1 | Job1 | 1 | 2
2 | Job2 | 2 | 3
-- Languages
ID | Language
1 | French
2 | English
3 | Spanish
你需要这样的东西:
$this->createQueryBuilder('job')
->leftJoin('job.language1', 'language1')
->leftJoin('job.language2', 'language2')
->where('language1.language IN (:languages)')
->orWhere('language2.language IN (:languages)')
->setParameter("languages", $languages)
->getQuery()
->getResult();
我也遇到了不同的问题,这就是为什么 Dougs 解决方案对我不起作用的原因。在解决了这个问题和他的解决方案的帮助下,我想出了这个:
$queryBuilder
->leftJoin('PathLanguage', 'language1', JOIN::LEFT_JOIN, "job.language1 = language1")
->leftJoin('PathLanguage', 'language2', JOIN::LEFT_JOIN, "job.language2 = language2")
->andWhere(
$queryBuilder->expr()->orX(
$queryBuilder->expr()->in("language1.name", ":languages"),
$queryBuilder->expr()->in("language2.name", ":languages")
)
)->setParameter("languages", $languages);