我有两个表services
和service_requests
。service_requests
表具有引用services
表的外键service_id
。
我必须从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)
生成的
$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查询。
3条答案
按热度按时间lf3rwulv1#
首先,如果你在cakePHP查询中使用select(),那么find('all')是不必要的,因此find()就足够了。然后,我认为你的执行问题可以通过放置-〉execute()来解决;在查询的结尾。它不常使用,但有时会有帮助。
ruyhziif2#
这可以通过表关联来实现
您的服务表:
您的请求表:
现在在控制器方法中:
有关查找查询的更多具体信息,请参见链接http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html
以及有关表关联的更多信息,请参见链接:http://book.cakephp.org/3.0/en/orm/associations.html
j9per5c43#
然后通过$service_requests-〉services访问关联的数据。
这是最干净、最简单的方法。
查看如何将它们链接在一起:)http://book.cakephp.org/3.0/en/orm/associations.html