我正在尝试构建带有分组的Doctrine ODM查询(我是Mongo的新手,我有很强的SQL背景(。
我想获得在给定时间段内有 2 个或更多显示器的所有结果。
public function findDisplayedForCompany(string $companyId, DateTime $start)
{
$qb = $this->createQueryBuilder();
$qb->field('interactor')->equals($companyId)
->field('interactionDate')->gte($start)
->group(['interacted' => 'interacted'], ['count' => 0])
->reduce('function (obj, prev) { prev.count++; }')
->field('count')
->gt('1');
$query = $qb->getQuery();
return $query->execute();
}
不幸的是,上面的代码没有给我任何结果。
在SQL中,它将类似于SELECT *, COUNT(*) count FROM x GROUP BY interacted HAVING COUNT(*) > 1
文档结构(非常简单(:
class Interaction
{
/**
* @MongoDBId
*/
protected $id;
/**
* @MongoDBReferenceOne(targetDocument="Company", storeAs="id")
* @var Company
*/
protected $interacted;
/**
* @MongoDBReferenceOne(targetDocument="Company", storeAs="id")
* @var Company
*/
protected $interactor;
/**
* @MongoDBField(type="date")
* @var DateTime
*/
protected $interactionDate;
public function __construct(Company $interacted, Company $interactor)
{
$this->interacted = $interacted;
$this->interactor = $interactor;
$this->interactionDate = new DateTime();
}
}
我找到了一些适合我需求的解决方法,但我对此不满意,所以我仍在寻求初始问题的帮助。
public function findDisplayedForCompany(string $companyId, $start)
{
$qb = $this->createQueryBuilder();
$qb->field('interactor')->equals($companyId)
->field('interactionDate')->gte($start)
->group(['company' => 'company'], ['count' => 0])
->reduce('function (obj, prev) { prev.count++; }');
$query = $qb->getQuery();
$results = $query->execute()->toArray();
$ids = [];
foreach ($results as $result) {
if ($result['count'] > 1) {
$ids[] = (string) $result['company'];
}
}
return $ids;
}