3

How I can execute a SQL query in CakePHP.

I want to make some like this code

    $employees = $this->Employee->find('all');

but introducing my own SQL statment.

3 Answers3

4

Insert into your Model a function that executes your SQL statment,

public function get_employees() {
     $sql = 'select * from employees';         
     $data = $this->query($sql);
     return $data;
 }

And call this function like this way:

 $employee = new Employee();
 $data = $employee->get_employees();
Cesar Loachamin
  • 2,740
  • 4
  • 25
  • 33
mgranjao
  • 104
  • 1
  • 1
  • 8
  • Its unnecessary. There is solution with one line below. http://stackoverflow.com/questions/22495160/cakephp-query-from-model/22505493#22505493 – sdagli Mar 19 '14 at 12:26
2

In model you can't write model name. Its already detected. Use only

$this->find('all');
sdagli
  • 121
  • 3
0

Assuming your statement is inside EmployeesController.php

$employeeRows = $this->employee->find('all', array('conditions'=>array('id' => 100)));

if you are in another controller, you have to load the model before the find

$this->loadModel('employee');

if you are in a view, you can write a helper and use raw sql

The cakephp website also offers the following controller logic

$this->Picture->query("SELECT * FROM pictures LIMIT 2;");
Soup Cup
  • 101
  • 1
  • 5