Search code examples
phpmysqldatabasecakephpjoincolumn

CakePHP, How to getting value from another table


I have 2 table on model , Table1 and Table2 Column on Table1

ID | Content1

Column on Table2

ID | table1_id | Content2

i want to display Content in Table1 on Table2 , how to join column?

thanks advance!


Solution

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

    In the controller:

    $data = $this->Model2->find('all');
    

    The generated query will be

    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