cakephp 3使用table获取所有内容。*

时间:2016-11-24 12:29:14

标签: php mysql cakephp

我正在使用cakePHP3查询构建器使用以下查询从两个表中获取记录,其中我想要table1中的所有列和table2中的选定列:

$this->loadModel('Table1');
$Table1 = $this->Table1->find('all', array('fields' => array('Table1.*'),'conditions'=>$conditions,'order'=>array('Table1.id'=>'DESC')))->contain(['Table2']);

但是我收到以下错误

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS `Table1__*` FROM Table1 Table1 LEFT JOIN Table2 Table2 ON ' at line 1

我是CakePHP3的新手。

2 个答案:

答案 0 :(得分:4)

为什么不使用查询构建器?

有很多方法可以做到这一点

$query= $this->Table1->find('all') 
    ->where($conditions)
    ->order(['Table1.id'=>'DESC'])
    ->contain(['Table2' => [
            'fields' => ['field1', 'field2']
        ]
    ]);

$query= $this->Table1->find('all') 
    ->select($this->Table1) // selects all the fields from Table1
    ->select(['Table2.field1', 'Table2.field2']) // selects some fields from Table2
    ->where($conditions)
    ->order(['Table1.id'=>'DESC'])
    ->contain(['Table2']);

$query= $this->Table1->find('all') 
    ->where($conditions)
    ->order(['Table1.id'=>'DESC'])
    ->contain(['Table2' => function($q) {
             return $q->select(['field1', 'field2']);
        }
    ]);

答案 1 :(得分:-2)

假设表之间的关系正确

示例条件数组

$conditions = ['Table2.id' > 1];

从表中选择行

 $table1 = $this->Table1->find()->select(['Table1.*'])->where($conditions)->contain(['Table2'])->order(['Table1.id'=>'DESC'])->toArray();

OR

$table1 => $this->Table1->find('all', array(
    'contain' => ['Table2'],
    'conditions' => $conditions,
    'fields' => ['Table1.*'],
    'order' => ['Table1.id'=>'DESC']
));

在这里,您有关于queryBuilder

的更多信息