我有两张桌子services
和service_requests
. service_requests
表有外键service_id
引用services
表。
我必须从services
哪里选择service_requests
数据services.id = service_requests.service_id
ORDER BY COUNT(service_requests.service_id) DESC
这就是我在控制器中所做的
$servicesTable = TableRegistry::get('services');
$featuredServices = $servicesTable->find('all')
->select(['ServiceRequests.service_id', 'count' => 'COUNT(ServiceRequests.service_id)'])
->select($servicesTable)
->join([
'table' => 'service_requests',
'alias' => 'ServiceRequests',
'conditions' => ['Services.id' => 'ServiceRequests.service_id'],
])
->group('service_id')
->order(['Count' => 'DESC'])
->limit(10);
$this->set('featuredServices', $featuredServices);
并打印为
if (!empty($featuredServices)):
foreach($featuredServices as $service):
echo $service->title;
endforeach;
endif;
但它不起作用。打印也echo $featuredServices;
只打印 sql 字符串SELECT.......
。这两个表都与我正在使用的控制器无关。
编辑 2
我想要这样的查询
SELECT ServiceRequests.service_id AS `ServiceRequests__service_id`, COUNT(ServiceRequests.service_id) AS `count`, Services.id AS `Services__id`, Services.service_category_id AS `Services__service_category_id`, Services.title AS `Services__title`, Services.description AS `Services__description` FROM services Services INNER JOIN service_requests ServiceRequests ON Services.id = ServiceRequests.service_id GROUP BY service_id ORDER BY Count DESC LIMIT 10
此 sql 查询在运行时工作正常,phpMyAdmin
并且此查询由debug($featuredServices)
of生成
$featuredServices = $servicesTable->find('all')
->select(['ServiceRequests.service_id', 'count' => 'COUNT(ServiceRequests.service_id)'])
->select($servicesTable)
->join([
'table' => 'service_requests',
'alias' => 'ServiceRequests',
'conditions' => ['Services.id' => 'ServiceRequests.service_id'],
])
->group('service_id')
->order(['Count' => 'DESC'])
->limit(10);
这仅在调试时生成 sql 查询。我怎样才能执行这个,以便我可以得到结果而不是 sql 查询。