4. 数据库操作
在Phalcon中操作数据库提供了基本的ORM映射方式以及更加复杂的PHQL方式。ORM映射方式支持不写SQL语句直接操作数据库,基本上已经提供了绝大多数使用场景的支持;另一种更为高级的PHQL方式,支持编写Phalcon化的SQL语句来操作数据库。这里不编写SQL语句,直接使用ORM映射本身提供的一切功能。
### 4.1 添加数据
如果我想添加一条数据,最基本的方式演示如下:
新建一个控制器DatabaseController
在控制器中添加InsertAction
在InsertAction中写入下列代码:
public function insertAction() { $customer = new Customer(); $customer->username = 'liyi'; $customer->password = '123456'; $ret = $customer->save(); if($ret){ print_r('插入成功'); } else { print_r('插入失败'); } } |
4.2 查询数据
1.find方法
Phalcon中提供了静态方法find,采用find方法可以返回表中符合条件的所有数据:
public function findAction() { $customers = Customer::find(); $result = []; foreach ($customers as $customer) { $result[] = [ 'username' => $customer->username, 'password' => $customer->password, ]; } $this->response->setContentType('application/json', 'UTF-8'); return $this->response->setJsonContent($result); } |
调用类的静态方法find()会返回包含有customer数据表内容的结果集,对于结果集的处理通常采用foreach进行遍历,如代码所示,对遍历的每一个对象调取属性值,然后赋值给关联数组。
2.findFirst方法
Phalcon中的findFirst方法与find方法的使用方式几乎无异,其区别在于findFirst方法的返回结果为单值,不需要通过foreach遍历获取每个值,在下面的代码中演示了查询数据库表中username字段值等于'liyi'的记录。
public function findfirstAction() { $customer = Customer::findFirst("username = 'liyi'"); $result = [ 'username' => $customer->username, 'password' => $customer->password, ]; $this->response->setContentType('application/json', 'UTF-8'); return $this->response->setJsonContent($result); } |