前段时间的一个项目是要对一个用yii1.1写的商城做修改,不怎么好写,不过比面向过程的ecshop好得多,之前刚开始改ecshop还真是头大
yii1.1其中数据库操作花了我不少时间去找各种例子进行测试,出于日后可能还要改的原因,我将数据库的一些操作改成了thinkphp的形式,代码如下
<?php
/**gcud数据库操作
* @version 20191231
*/
class gcudDb
{
private $TableName;
private $Conditions;
private $ConditionsParameters;
private $FieldsString;
private function getDbCommand()
{
return \Yii::app()->db->createCommand();
}
private function BuildCondition()
{
$this->ConditionsParameters = [];
$this->ConditionsParameters['fieldString'] = '';
$this->ConditionsParameters['parameters'] = [];
if ($this->Conditions)
foreach ($this->Conditions as $Key => $Value) {
$this->ConditionsParameters['fieldString'] .= " and $Key=:$Key";
$this->ConditionsParameters['parameters'][":$Key"] = $Value;
}
$this->ConditionsParameters['fieldString'] = ltrim($this->ConditionsParameters['fieldString'], ' and ');
}
public static function name($TableName)
{
$Table = new static();
$Table->TableName = "{{_$TableName}}";
return $Table;
}
public function field($FieldString)
{
$this->FieldsString = $FieldString;
return $this;
}
public function where($field, $value)
{
$this->Conditions[$field] = $value;
return $this;
}
public function insert($Data)
{
self::getDbCommand()->insert($this->TableName, $Data);
}
public function delete()
{
$this->BuildCondition();
self::getDbCommand()->delete($this->TableName, $this->ConditionsParameters['fieldString'],
$this->ConditionsParameters['parameters']);
}
public function find()
{
$this->BuildCondition();
return self::getDbCommand()->select($this->FieldsString)
->from($this->TableName)->where($this->ConditionsParameters['fieldString'],
$this->ConditionsParameters['parameters'])->queryRow();
}
public function column($Field)
{
$this->BuildCondition();
$Data = self::getDbCommand()->select($Field)
->from($this->TableName)->where($this->ConditionsParameters['fieldString'],
$this->ConditionsParameters['parameters'])->queryAll();
$ReturnData = null;
foreach ($Data as $Item) {
$ReturnData[] = $Item[$Field];
}
return $ReturnData;
}
public function value($Field)
{
$this->BuildCondition();
$Data = self::getDbCommand()->select($Field)->from($this->TableName)
->where($this->ConditionsParameters['fieldString'],
$this->ConditionsParameters['parameters'])->queryRow();
return $Data[$Field];
}
public function count()
{
$this->BuildCondition();
$Data = self::getDbCommand()->select('count(1) gcudcount')
->from($this->TableName)->where($this->ConditionsParameters['fieldString'],
$this->ConditionsParameters['parameters'])->queryRow();
return $Data['gcudcount'];
}
public function update($Data)
{
$this->BuildCondition();
self::getDbCommand()->update($this->TableName, $Data,
$this->ConditionsParameters['fieldString'],
$this->ConditionsParameters['parameters']);
}
}
db操作风格是5.1的,where操作仅支持直接的deng'yu
来源:oschina
链接:https://my.oschina.net/u/3470006/blog/3159274