如何从cakephp 3.6中的一个表中选择所有记录,从另一个表中选择一些记录

问题描述 投票:0回答:2

SELECT myTable。*,otherTable.foo,otherTable.bar ......

我们如何在cakephp中编写上述查询?我尝试了这个,但没有奏效。

$data = $this->Articles->find()->select(['Articles.*','Categories.name'])->innerJoineWith('Categories');

它给了我SELECT Fees.* ASFees __ * .附近的错误

因此,我必须编写文章表的所有列。

$data = $this->Articles->find()->select(['Articles.id','Articles.name','Articles.title','Articles.description','Categories.name'])->innerJoineWith('Categories');

cakephp有什么解决方案吗?请告诉我。谢谢。

php mysql cakephp cakephp-3.0
2个回答
0
投票

你可以这样做:

$this->Articles->find('all')->contain(['Categories' => function($q) {
                    return $q->select('Categories.name');
                }])->select($this->Articles);

select语句中的$this->Articles将从Articles表中获取所有记录,$q->select('Categories.name')将仅从关联的Categories表中获取Category名称。

参考:https://github.com/cakephp/cakephp/issues/7913


0
投票
$data = $this->Articles->find()
        ->select($this->Articles)
        ->select(['Categories.name'])
        ->innerJoineWith('Categories');
© www.soinside.com 2019 - 2024. All rights reserved.