刚认识zf2时, 对数据模型比较陌生. 接触一段时间后, 才能慢慢上手. 故留下笔记供大家参考.
1.使用方法
以下为获取一行记录封装好的函数.
/**
* select 获取一条记录
*
* @param array|string $where : 兼容getRow(1)
* @param array $extra
* @return Array
*/
public function getRow($where = '', $extra = array())
{
$sql = $this->sql;
$select = $sql->select();
if (isset($where['or']) && is_array($where))
{
$select->where($this->_getWhere($where['or']), 'OR');
$where['or'] = '';
unset($where['or']);
}
if ($where)
{
$select->where($this->_getWhere($where));
}
if (isset($extra['join']))
{
//$extra['join'] = array(array('t2' => 'table2'), 'name' => 't2.name', '*', 'left');
$select->join(
$extra['join'][0],//第二个表, 别名用法
$extra['join'][1],
isset($extra['join'][3]) ? $extra['join'][3] : '*',
isset($extra['join'][4]) ? $extra['join'][4] : 'left'
);
}
isset($extra['group']) && $select->group($extra['group']);
isset($extra['having']) && $select->having($extra['having']);
isset($extra['columns']) && $select->columns($extra['columns']);
$this->log('getRow='.$this->sql->getSqlStringForSqlObject($select));
$rowset = $this->selectWith($select);
return $this->iconv($rowset->current(), true);
}
/**
* 解析where
*
* @param array $where
* array(
* 'id' => '4',
* 'id' => array(4, 5), //in 操作
* 'like' => array('name' => 'abc', 'word' => 'hello'),
* 'between' => array('id' => array('3', '12')),
* 'not' => array('name' => 'abc', 'word' => 'hello'),// name != 'abc' and word != 'hello'
* 'or' => array('name' => 'abc', 'word' => 'hello'),//生成 where name = 'abc' or word = 'hello' and ...
* )
* @return array
*/
private function _getWhere($where)
{
$whereArr = array();
if (!is_array($where))
{
$whereArr = array($this->primaryKey => $where);
}
elseif (is_array($where))
{
foreach ($where as $key => $val)
{
switch ($key)
{
case 'like' :
foreach ($val as $itemKey => $itemVal) {
$whereArr[] = $this->sql->select()->where->like($itemKey, $itemVal);
}
break;
case 'not' :
foreach ($val as $itemKey => $itemVal) {
$whereArr[] = new Operator($itemKey, '!=', $itemVal);
}
break;
case 'between' :
foreach ($val as $itemKey => $itemVal) {
$whereArr[] = $this->sql->select()->where->between($itemKey, $itemVal[0], $itemVal[1]);
}
break;
case 'greater' :
foreach ($val as $itemKey => $itemVal) {
$whereArr[] = new Operator($itemKey, '>=', $itemVal);
}
break;
default:
$whereArr[$key] = $val;
}
}
}
return $whereArr;
}
当获取多行 getList 时以此类推..
2. 关于代码的复用
我目前的方式是把getRow, getList, insert, update, delete 封装到模型的继承类中, 这样就不必为每个模型写这些基本操作. 当然若遇到业务复杂时, 可单独在模型中开小灶, 单独写.
Author : xlhui1985@126.com
Time : 2013.8.30 周五