2014-03-19 39 views
2

我如何在CakePHP中执行SQL查询。CakePHP,模型查询

我想要做一些像这样的代码

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

但介绍我自己的SQL statment。

回答

3

插入到你的模型,执行你的SQL statment功能,

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

而调用这个函数像这样:

$employee = new Employee(); 
$data = $employee->get_employees(); 
+0

它是不必要的。有一条线在下面。 http://stackoverflow.com/questions/22495160/cakephp-query-from-model/22505493#22505493 – sdagli

1

在模型,你可以不写型号名称。它已经被检测到。仅使用

$this->find('all'); 
0

假设你的说法是内部EmployeesController.php

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

如果你是在另一个控制器,你必须加载模型之前找到

$this->loadModel('employee'); 

如果你是在一个视图中,你可以写一个帮手并使用原始的sql

cakephp网站al所以提供以下控制器逻辑

$this->Picture->query("SELECT * FROM pictures LIMIT 2;");