1
我试图获得我附加的查询的聚合结果。我一直在挣扎几天,我似乎找不到解决方案。帮助将不胜感激CakePHP 3.x-如何在查找查询中使用总和
这些机型:
class EventsPromotersTable extends Table
{
public function initialize(array $config)
{
$this->addAssociations([
'belongsTo' => ['Events', 'Promoters'],
'hasMany' => ['Payments']
]);
}
}
class EventsTable extends Table
{
public function initialize(array $config)
{
$this->addAssociations([
'hasMany'=> ['TicketTypes'],
'belongsToMany' => ['EventsPromoters' => ['through' => 'EventsPromoters']]
]);
}
}
class PromotersTable extends Table
{
public function initialize(array $config)
{
$this->addAssociations([
'belongsTo' => ['MultimediaFiles'],
'belongsToMany' => ['EventsPromoters' => ['through' => 'EventsPromoters']]
]);
}
}
class PaymentsTable extends Table
{
public function initialize(array $config)
{
$this->addAssociations([
'belongsTo' => ['Promoters'],
'hasMany' => ['Sales']
]);
}
}
class SalesTable extends Table
{
public function initialize(array $config)
{
$this->addAssociations([
'belongsTo' => ['TicketTypes', 'Payments']
]);
}
}
class TicketTypesTable extends Table
{
public function initialize(array $config)
{
$this->addAssociations([
'belongsTo' => ['Events'],
'hasMany' => ['Sales']
]);
}
}
我试图检索TicketTypes
(sum(Sales.quantity)
)由Promoters
卖出金额。
这是我的查找方法:
$query= $this->EventsPromoters
->find()
->contain([
'Promoters' => function($q) {
return $q
->select(['Promoters.id', 'Promoters.name'])
;
},
'Payments.Sales.TicketTypes' => function($q) {
return $q
->select(['TicketTypes.id', 'TicketTypes.name'])
;
}
])
->innerJoinWith('Events', function ($q) use($event_slug) {
return $q->where(['Events.slug' => $event_slug]);
})
;
find方法是否工作正常。现在我必须添加聚合,但我不知道如何。
我希望是这样的:
'promoter' => object(Cake\ORM\Entity) {
'id' => (int) 101,
'name' => 'Lucas Moura',
'ticket_types' => [
(int) 0 => object(Cake\ORM\Entity) {
'id' => (int) 101,
'name' => 'Primera Preventa',
'sales' => 3 <<<<<< AGGREGATION
'[new]' => false,
'[accessible]' => [
'*' => true
],
'[dirty]' => [],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[repository]' => 'TicketTypes'
}
(int) 1 => object(Cake\ORM\Entity) {
'id' => (int) 102,
'name' => 'Palco VIP',
'sales' => 9 <<<<<< AGGREGATION
'[new]' => false,
'[accessible]' => [
'*' => true
],
'[dirty]' => [],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[repository]' => 'TicketTypes'
}
任何想法?谢谢!
你读过[**关于使用SQL函数**的文档](http://book.cakephp.org/3.0/en/orm/query-builder.html#using-sql-functions)吗?你面临的实际技术问题是什么? “我不知道如何”为解释留下了很多空间。 – ndm
嗨@ndm。我不知道如何添加聚合(总和)。请看我期望的代码。我想检索发起人销售的票类型的金额,而没有关于付款和销售的信息,只是金额。 – dfc
您尝试过使用[Virtual fields](http://book.cakephp.org/3.0/en/orm/entities.html#creating-virtual-fields)吗? –