Home > php教程 > php手册 > body text

Zend Framework 2.0 (zf2) 进阶数据库操作

WBOY
Release: 2016-06-21 08:51:25
Original
911 people have browsed it

  zf2完全重写了Zend1的数据库组件,但是目前手册给的例子都弱爆了,只能自己整理一些Zend\Db\TableGateway用例如下:

  首选的操作DB方式还是继承TableGateway,比如现在有一个posts表需要操作,新建一个类如下

  class Posts extends Zend\Db\TableGateway\TableGateway

  {

  }

  实例化这个类并传入Zend\Db\Adapter\Adapter即可连接数据库,此处并非重点,假设实例化后的TableGateway为$postTable,我们需要这样操作posts表:

  WHERE 链式操作

  zf2推荐的查询方式为链式操作

  $select = $postTable->getSql()->select();

  $select->where('id > 5')->order('id DESC')->limit(10);

  $resultSet = $postTable->selectWith($select);

  $result = $resultSet->toArray();

  WHERE 闭包操作

  zf2还支持闭包式的操作,上例可以以闭包方式改写成:

 

  $select = $postTable->getSql()->select();

  $select->where(function($where){

  $where->lessThan('id', 10);

  $where->greaterThan('id', 5);

  return $where;

  })->order('id DESC')->limit(10);

  WHERE AND复合条件

  而当where条件为复合条件时,可以这样写:

 

  $select->where(

  array('id > 30')

  )->where(

  array('id

  );

 

  将会生成以下SQL

  SELECT "posts".* FROM "posts" WHERE id > 30 AND id

  WHERE OR 复合条件

  如果要将Where查询的默认链接为AND,如果想要更改为OR,可以这样写:

 

  $select->where(

  array('id > 30')

  )->where(

  array('id

  );

  SQL:

  SELECT "posts".* FROM "posts" WHERE id > 30 OR id

  还可以这样写,效果是一样。这是通过魔术方法__call()实现的。

  $where = $select->where;

  $where->lessThan('id', 10);

  $where->or;

  $where->greaterThan('id', 30);

 

  WHERE 复杂条件

  如果查询条件进一步复杂,比起链式操作来,闭包操作更具有灵活性,比如:

  $select->where(function($where){

  $subWhereForId = clone $where;

  $subWhereForTitle = clone $where;

  $subWhereForId->lessThan('id', 10);

  $subWhereForId->or;

  $subWhereForId->greaterThan('id', 20);

  $where->addPredicate($subWhereForId);

  $subWhereForTitle->equalTo('title', 'a');

  $subWhereForTitle->or;

  $subWhereForTitle->equalTo('title', 'b');

  $where->addPredicate($subWhereForTitle);

  return $where;

  });

  等同于SQL

  SELECT "posts".* FROM "posts" WHERE ("id" '20') AND ("title" = 'a' OR "title" = 'b');

 

  EvaEngine的改进

  在EvaEngine中,可以使用完整的链操作,最开始的例子在EvaEngine里可以这样写:

  $result = $postTable->where('id > 5')->order('id DESC')->limit(10)->find();

原文地址:http://avnpc.com/pages/advanced-database-select-usage-in-zf2



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template