CakePHP 3:从多个表中选择数据

时间:2016-07-06 07:26:30

标签: mysql cakephp model-associations cakephp-3.2

我有两张表servicesservice_requestsservice_requests表具有引用service_id表的外键services

我必须从servicesservice_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

此{s}查询在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 个答案:

答案 0 :(得分:0)

将表链接在一起,然后通过$ service_requests-> services访问相关数据。

这是最干净,最简单的方法。

看看这个如何将它们链接在一起:) http://book.cakephp.org/3.0/en/orm/associations.html

答案 1 :(得分:0)

这可以通过表关联来实现

您的服务表:

public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('services');
    $this->displayField('id');
    $this->primaryKey('id');

   ======== use this line ===============

    $this->hasOne('Requests'); // for one to one association

  ======== OR =============== 

   $this->hasMany('Requests'); // for one to many association

   ============ more specific ==========

    $this->hasMany('Requests', array(
        'foreignKey' => 'service_id'
    ));     
}

您的RequestsTable:

public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('requests');
    $this->displayField('id');
    $this->primaryKey('id');

   ========= add this line ============

   $this->belongsTo('Services');

   ========= or more specific ============

    $this->belongsTo('Services', array(
        'foreignKey' => 'service_id',
        'joinType' => 'INNER',
    ));

}

现在在控制器方法中:

 public function test()
 {
    $this->loadModel('Services');       

    $query = $this->Services->find('all', array('contain' => array('Requests')))->limit(10);

    //debug($query);
    $services= $query->toArray();
    debug($services);
    $this->set('services', $services);
} 

有关查找查询的更多具体信息,请参阅链接 http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html

以及有关表关联的更多信息,请参阅链接: http://book.cakephp.org/3.0/en/orm/associations.html

答案 2 :(得分:0)

首先,如果你在cakePHP查询中使用select(),那么找不到(' all'),因此find()就足够了。 然后,我认为您的执行问题可以通过放置 - > execute();在查询结束时。它并不经常使用,但它有时会有所帮助。