user3435737
user3435737

Reputation: 33

CakePHP, Query from Model

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.

Upvotes: 3

Views: 2076

Answers (3)

Soup Cup
Soup Cup

Reputation: 121

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

Upvotes: 0

sdagli
sdagli

Reputation: 121

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

$this->find('all');

Upvotes: 2

mgranjao
mgranjao

Reputation: 104

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

Upvotes: 4

Related Questions