【问题标题】:cakephp 3 fetch all by using table.*cakephp 3 使用 table.* 获取所有内容
【发布时间】:2016-11-24 12:29:13
【问题描述】:

我正在使用 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 的新手。

【问题讨论】:

  • 请参考正确的语法:$this->Table1->find('all', array( 'joins' => array( array( 'table' => ‘table1’, 'alias' => ‘table’, 'type' => 'INNER', 'conditions' => array( ‘table1.id = table2.id’ ) ) ), 'conditions' => $conditions, 'fields' => array(‘table1.*’, ‘table2.field1, table2.field2’), ));
  • 使用你的代码我得到这个错误: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__*, Table2.field1, Table2.field2 AS Table2__field1, Prod' at line 1
  • 看起来 CakePHP 无法处理 .*

标签: php mysql cakephp


【解决方案1】:

为什么不使用查询生成器?

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

$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']);
        }
    ]);

【讨论】:

  • 虽然在这种情况下没有必要,Table1 的所有字段都会被选中。听起来更像是 OP 正在寻找限制收容区域,即Table2
  • @ndm 事实上。我使用select($this->Table1) 来避免使用 Table2 中的所有字段
  • 是的,但这会导致关联不包含在结果中,这没有多大意义;)据我了解,OP 需要来自Table2 的一些特定字段。
  • 是的,现在我知道我误读了这个问题,你可能是对的
【解决方案2】:

假设表之间的关系正确

示例条件数组

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

从表中选择行

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

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

这里有更多关于queryBuilder的信息

【讨论】:

  • 即使按照您 (@Jacek) 的建议更改了查询,我仍然遇到同样的错误! :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
相关资源
最近更新 更多