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 Answers 3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Its unnecessary. There is solution with one line below. stackoverflow.com/questions/22495160/cakephp-query-from-model/…
2

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

$this->find('all');

Comments

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;");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.