简体   繁体   English

CakePHP,从模型查询

[英]CakePHP, Query from Model

How I can execute a SQL query in CakePHP. 我如何在CakePHP中执行SQL查询。

I want to make some like this code 我想做一些像这样的代码

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

but introducing my own SQL statment. 但要介绍我自己的SQL语句。

Insert into your Model a function that executes your SQL statment, 将执行SQL语句的函数插入模型中,

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

In model you can't write model name. 在模型中,您无法输入模型名称。 Its already detected. 它已经被检测到。 Use only 仅使用

$this->find('all');

Assuming your statement is inside EmployeesController.php 假设您的语句在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 如果您在视图中,则可以编写一个助手并使用原始sql

The cakephp website also offers the following controller logic cakephp网站还提供以下控制器逻辑

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM