我在model上有2个表,Table1和Table2
表1中的列
ID | Content1
表2上的列
ID | table1_id | Content2
我想在Table2的Table1中显示Content,如何加入列?
谢谢提前!
最佳答案
Model\Model1.php
<?php
App::uses('AppModel', 'Model');
class Model1 extends AppModel {
public $useTable = 'table1';
}
Model\Model2.php
<?php
App::uses('AppModel', 'Model');
class Model2 extends AppModel {
public $useTable = 'table2';
public $belongsTo = array(
'Model1' => array(
'className' => 'Model1',
'foreignKey' => 'table1_id'
)
);
}
在控制器中:
$data = $this->Model2->find('all');
生成的查询将是
SELECT `Model2`.`id`, `Model2`.`table1_id`, `Model2`.`content2`, `Model1`.`id`, `Model1`.`content1` FROM `db`.`table2` AS `Model2` LEFT JOIN `cake244`.`table1` AS `Model1` ON (`Model2`.`table1_id` = `Model1`.`id`) WHERE 1 = 1