我是CakePHP的新手,当我试图绕着桌子工作时,我遇到了从两个表中获取特定colmns的问题。我想要实现的是:
SELECT categories_1.category_id,categories_2.name FROM categories_1 JOIN categories_2 ON categories_2.category_id = categories_1.category_id
我知道我能做到:
$query=$this->Categories1->find('all')->contain(['Categories2'])
然而这种方式我得到整个表categoires_2作为内部数组,这使得结构更复杂,并从第二个表添加不必要的列。
我尝试按照文档进行操作,但我提出的代码并没有真正起作用:
$query=$this->Categories1->find('all')
->select('Categories2.name','Categories1.category_id')
->join([
'table' => 'categories_2',
'alias' => 'Categories2',
'conditions' => array('Categories2.category_id' => 'Categories1.category_id')
]);
我很感激帮助纠正代码...... 感谢
编辑: 蛋糕正在生成以下sql代码:
SELECT Categories2.name AS `Categories2__name` FROM categories_1 Categories1 INNER JOIN categories_2 Categories2 ON Categories2.category_id = :c0
答案 0 :(得分:2)
您可以指定要返回的字段
$query=$this->Categories1->find('all')->contain(
['Categories2' => [
'fields' => ['field1', 'field2']
]
]
)