将SQL查询转换为CakePHP

时间:2018-10-21 13:08:10

标签: sql cakephp

我有此SQL查询,我需要将其转换为CakePHP。我使用了该网站[http://dogmatic69.com/sql-to-cakephp-find-converter][1]来转换代码,但无法按照我想要的方式工作。没有结果。

我认为这是因为它创建了一个空数组 这是SQL代码:

+----+--------+--------+--------+--------+
| ID | ItemNo | Label  | Series | Amount |
+----+--------+--------+--------+--------+
|  1 |    111 | Baer   | Toys   |      9 |
|  2 |    111 | Baer   | Toys   |      9 |
|  3 |    222 | Flower | Garden |      8 |
|  4 |    222 | Flower | Garden |      8 |
|  5 |    222 | Flower | Garden |      8 |
+----+--------+--------+--------+--------+

这是网站给我的结果:

SELECT shops.phone1 FROM galleries , albums , shops
WHERE  galleries.album_id = albums.id and albums.shop_id = shops.id and galleries.id = 210

但是代码不起作用。

任何想法可能有什么问题吗?

谢谢

1 个答案:

答案 0 :(得分:1)

有很多方法可以实现这一目标。 如果正确定义了关联,则可以执行以下操作:

$data = $this->Shops->find('all')
             ->contain(['Galleries','Albums'])
             ->fields(['Shops.phone1'])
             ->where(['Galleries.id' => 210]);

否则,您可以使用自定义联接来生成查询:

$data = $this->Shops->find('all') 
                     ->join([
                           'albums' => [
                                 'table' => 'albums',
                                 'type' => 'INNER', // define your join type here
                                 'conditions' => 'albums.shop_id = Shops.id',
                                  ],
                           'galleries' => [
                                  'table' => 'galleries',
                                  'type' => 'INNER', // define your join type here
                                  'conditions' => 'galleries.album_id=albums.id',
                             ]
                     ])
                   ->select(['Shops.phone1'])
                   ->where(['galleries.id' => 210]);

进一步阅读:Cakephp -> Query Builder -> Adding Joins