CakePHP,如何从另一个表中获取价值

时间:2014-02-06 05:15:56

标签: php mysql database cakephp joincolumn

我在模型,Table1和Table2上有2个表 表1上的专栏

ID | Content1

表2上的专栏

ID | table1_id | Content2

我想在Table2上的Table1中显示内容,如何加入列?

感谢提前!

1 个答案:

答案 0 :(得分:2)

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