Your Location is: Home > Cakephp

CakePHP Inner Join Not Working

From: Wellington View: 4847 Alimon Karim 

Question

I am trying to convert this mysql query into cakephp, but it's not working.

Here is my mysql query

SELECT r.id, p.name, r.paid, p.created
       FROM patients p
       INNER JOIN reports r ON p.id = r.patient_id
       AND doctor_name LIKE '%dr.saidul%'

In cakephp I have tried bellow code

$query_options = array();
            $query_options['fields'] = array( 'Report.id', 'Report.paid','Patient.name','Patient.created' );
            $query_options['conditions'] = array( 'Patient.doctor_name'=>'%dr.saidul%');
            $query_options['joins'] = array('table' => 'Report',
                                    'type' => 'INNER',
                                    'conditions' => array(
                                        'Patient.id = Report.id',
                                    )
                                );

            $patientlist=$this->Patient->find('all', $query_options);

After check sql_dump it's giving me bellow result

 SQL Query: SELECT `Report`.`id`, `Report`.`paid`, `Patient`.`name`, `Patient`.`created` FROM `diagnosis`.`patients` AS `Patient` LEFT JOIN `diagnosis`.`upazilas` AS `Upazila` ON (`Patient`.`upazila_id` = `Upazila`.`id`) LEFT JOIN `diagnosis`.`zilas` AS `Zila` ON (`Patient`.`zila_id` = `Zila`.`id`) LEFT JOIN `diagnosis`.`doctors` AS `Doctor` ON (`Patient`.`doctor_id` = `Doctor`.`id`) INNER JOIN `diagnosis`.`Report` ON (`Patient`.`id` => `Report`.`id`) WHERE `Patient`.`doctor_name` = '%dr.saidul%' 

Here Error : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=> Report.id) WHERE Patient.doctor_name = '%dr.saidul%'' at line 1

Best answer

I have submitted the cakephp inner join code please check it

$query_options = array();
            $query_options['fields'] = array( 'reports.id', 'reports.paid','Patient.name','Patient.created','Patient.doctor_name' );
            $query_options['conditions'] = array( 'Patient.doctor_name'=>'%dr.saidul%');
            $query_options['joins'] = array(
                                array('table' => 'reports',
                                'type' => 'INNER',
                                'conditions' => array(
                                    'Patient.id = reports.id',
                                    )
                                )
                            );
            $patientlist=$this->Patient->find('all', $query_options);