Yii 1.0 数据库操作 增、删、改、查 、对象转数组
$objectResult=Post::model()->findAll($condition,$params);?
$objectResult=Post::model()->findAll("username=:name",array(":name"=>$username));?
$objectResult=RepairItem::model()->findAll("orderno=:orderno and orderpostid=:orderpostid",array(":orderno"=>$orderInfo['orderno'],':orderpostid'=>$orderInfo['orderpostid']));?
$infoArr = NewsList::model()->findAll("status = '1' ORDER BY postid DESC limit 10 "); ? 2、根據主鍵查詢一個集合,可以使用多個主鍵 findAllByPk
$objectResult=Post::model()->findAllByPk($postIDs,$condition,$params);?
$objectResult=Post::model()->findAllByPk($postid,"name like :name and age=:age",array(':name'=>$name,'age'=>$age)); $objectResult=Post::model()->findAllByPk(array(1,2)); ? 3、根據條件查詢一個集合,可以是多個條件,把條件放到數組里面 findAllByAttributes
$objectResult=Post::model()->findAllByAttributes($attributes,$condition,$params);
$objectResult=Post::model()->findAllByAttributes(array('username'=>'jack')); ? 4、根據SQL語句查詢一個數組 findAllBySql
$arrResult=Post::model()->findAllBySql($sql,$params);?
$arrResult=Post::model()->findAllBySql("select * from tbl_post where username like :name",array(':name'=>'?%')); 5、根據主鍵查詢出一個對象 eg:findByPk(1);
$arrResult=Post::model()->findByPk($postID,$condition,$params); $arrResult=Post::model()->findByPk(1); 6、根據條件查詢出一組數據,【可能是多個,但是他只返回第一行數據】
$arrRow=Post::model()->find($condition,$params); $arrRow=Post::model()->find('username=:name',array(':name'=>'jack')); 7、根據條件查詢一組數據,【可以是多個條件,把條件放到數組里面,查詢的也是第一條數據】
$objectResult=Post::model()->findByAttributes($attributes,$condition,$params); $objectResult=Post::model()->findByAttributes(array('username'=>'objectResult')); ? 8、根據SQL語句查詢一組數據,【查詢的也是第一條數據】
$objectResult=Post::model()->findBySql($sql,$params); $objectResult=Post::model()->findBySql("select * from objectResult where username=:name",array(':name'=>'objectResult')); ? 9、通過CDbCriteria類find查詢出一個對象?
$criteria=new CDbCriteria; ?
$criteria->select='username';?
// 限制顯示哪些字段 ?
$criteria->condition='username=:username'; ? ??
//一個查詢條件用aCondition.多條件用addCondition $criteria->params=array(":username=>'jack'");?
$criteria->order = "postsort DESC";
?$criteria->limit = "3";?
$post=Post::model()->find($criteria); ?
$criteria = new CDbCriteria();? $criteria->select = 'table_name,model_id,sum(amount) total';? $criteria->group = 'table_name,model_id';? $criteria->addCondition("$nIdcId=4");//也可以$criteria->condition = "$nIdcId=4";? $aResult = accessory_info::model()->findAll($criteria);? 10、多條件查詢的語句$criteria = new CDbCriteria; ? ? ?
$criteria->addCondition("postid=1");?
//等同于 where postid = 1 ?
$criteria->addInCondition('postid', array(1,2,3,4,5));?
//等同于 where postid IN (1,2,3,4,5,); ?
$criteria->addNotInCondition('postid', array(1,2,3,4,5));
//等同于 NOT IN (1,2,3,4,5,)?
$criteria->addCondition('postid=1','OR');
//等同于 OR而非AND ?
$criteria->addSearchCondition('username', 'jack');
//等同于 where name like '%jack%' ?
$criteria->addBetweenCondition('postid', 1, 4);
// 等同于 between 1 and 4 $criteria->compare('postid', 1); ? ?
//根據你的參數自動處理成addCondition或者addInCondition. $criteria->compare('postid', array(1,2,3)); ??
//數組就會調用addInCondition ? ? ?
$criteria->select = 'postid,parentid,name';?
//限制顯示哪些字段 ?
$criteria->join = 'xxx';?
//連接表 ?$criteria->with = 'xxx';?
//調用relations ??
$criteria->limit = 10; ? ?
//取1條數據,如果小于0,則不作處理 ?
$criteria->offset = 1; ??
//兩條合并起來,則表示 limit 10 offset 1,或者代表了。limit 1,10 ?
$criteria->order = 'xxx DESC,XXX ASC' ;
//排序條件 ?
$criteria->group = 'group 條件'; ?
$criteria->having = 'having 條件 '; ?
$criteria->distinct = FALSE; //是否唯一查詢 二、查詢個數,判斷查詢是否有結果
根據一個條件查詢一個集合有多少條記錄,返回一個int型數字?
$intCount=Post::model()->count($condition,$params);?
$intCount=Post::model()->count("username=:name",array(":name"=>$username)); ??
根據SQL語句查詢一個集合有多少條記錄,返回一個int型數字?
$intCount=Post::model()->countBySql($sql,$params);?
$intCount=Post::model()->countBySql("select * from objectResult where username=:name",array(':name'=>'objectResult')); ??
根據一個條件查詢查詢得到的數組有沒有數據,有數據返回一個true,否則沒有找到?
$boolExists=Post::model()->exists($condition,$params);?
$boolExist=Post::model()->exists("name=:name",array(":name"=>$username)); 三、添加的方法
$objectPost = new Post; ? ? ? ?
$objectPost->username = $username;?
$objectPost->password = $password;?
或許?
$objectPost->attributes = $arrNewData;?
if($objectPost->save()){ ? ??
$intPostId= $objectPost->primaryKey;?
//生成主鍵id ? ?
echo "添加成功";?
}else{ ? ??
echo "添加失敗";?
} 四、修改的方法
Post::model()->updateAll($attributes,$condition,$params);?
$count =Post::model()->updateAll(array('username'=>'11111','password'=>'11111'),'password=:pass',array(':pass'=>'1111a1'));
if($count > 0){ ? ??
? ? echo "修改成功";?
}else{ ? ?
echo "修改失敗";
?} ?
$rt = PostList::model()->updateAll(array('status'=>'1'),'staff_postid=:staff AND host_postid=:host',array(':staff'=>$staff_postid,':host'=>$host_postid)); Post::model()->updateByPk($pk,$attributes,$condition,$params); $count=Post::model()->updateByPk(1,array('username'=>'jack','password'=>'jack'));?
$count=Post::model()->updateByPk(array(1,2),array('username'=>'jack1','password'=>'jack1'),'username=:name',array(':name'=>'jack'));?
if($count > 0){ ? ?
echo "修改成功";?
}else{ ? ?
echo "修改失敗";
?} ?
Post::model()->updateCounters($counters,$condition,$params); $count=Post::model()->updateCounters(array('status'=>1),'username=:name',array(':name'=>'jack'));
?if($count > 0){ ? ??
echo "修改成功";?
}else{ ? ?
echo "修改失敗";?
}
?//array('status'=>1)代表數據庫中的post表根據條件username='jack',查詢出的所有結果status字段都自加1 五、刪除的方法
//deleteAll Post::model()->deleteAll($condition,$params);?
$count = Post::model()->deleteAll('username=:name and password=:pass',array(':name'=>'jack',':pass'=>'jack'));?
$count = Post::model()->deleteAll('postid in("1,2,3")');
//刪除postid為這些的數據?
if($count>0){ ? ??
echo "刪除成功";?
}else{ ? ??
echo "刪除失敗";?
} ??
//deleteByPk?
Post::model()->deleteByPk($pk,$condition,$params);?
$count = Post::model()->deleteByPk(1);?
$count =Post::model()->deleteByPk(array(1,2),'username=:name',array(':name'=>'jack'));?
if($count>0){ ? ??
echo "刪除成功";
?}else{ ? ?
echo "刪除失敗";?
} 六、執行原生的SQL語句
$sql = "select t.*, t1.userphone, t1.truename, t1.usermail from {{member_contact}} t left join {{member}} t1 on t.userid = t1.userid where t.contactid in (1,2,3)";?
$arrRows=Yii::app()->db->createCommand($sql)->query();?
foreach ($arrRows as $k => $v){ ? ?} 七、事務處理 【多表更新插入操作請使用事務處理】
$transaction = Yii::app()->db->beginTransaction();?
try{ ? ? ? ? ? ? ? ??
$arrOrderProfile = array( ? ? ? ? ? ? ? ? ? ??
'orderid'=> $orderId, ? ? ? ? ? ? ? ? ? ?
'userip'=> $userip,
? ? ? ? 'contactid' => $contactId,
'updatetime'=> $now?
); ? ? ? ? ? ? ? ??
$modelOrderProfile = new RepairOrderProfile();
? ? $modelOrderProfile->attributes = $arrOrderProfile;
if(!$modelOrderProfile->save()){?
throw new CException('維修訂單生成失敗,通知事務回滾');
} ? ? ? ? ? ? ? ??
$recordCounter = Counter::model()->updateByPk(1,array('max_id'=>$orderId));
? ? if($recordCounter <= 0 )?
throw new CException('訂單計數器更新失敗,通知事務回滾');
$transaction->commit(); //提交事務會真正的執行數據庫操作?
}catch(Exception $e){
file_put_contents('action.log', $e->getCode().':'.$e->getMessage().'--'.date('Y-m-d H:i:s',time()),FILE_APPEND); ? ?$transaction->rollback();
} ??
八、對象轉換為數組
/**?
?* 簡化findall數據??* */ ?
function simplifyData($data){ ?
? ? foreach($data as $key=>$val){ ?
? ? ? ? $newData[$key] = $val->attributes; ?
? ? } ?
? ? return $newData; ?
} ? 第二種是使用很簡單的方法:
[html] view plain copy
$products = ProTuan::model()->findAll($criteria); ?
$products = json_decode(CJSON::encode($products),TRUE); ?
作用是就先將findAll結果先轉成JSON格式,然后再轉為數組.
至于findALL轉為JOSN格式其實就是使用
CJSON::encode ?
九、php 事務處理
當在一個應用執行一些查詢時, ?每次讀取 或 寫入數據庫中的信息, ?確保數據庫不是只執行了一部分查詢, 這一點非常重要.
一個事務處理, ?在 Yii ?的代表是一個CDbTransaction ?實例, may be initiated in this case:
開始事務處理.
逐個執行查詢. ?任何對數據庫的更新對于外部都是不可見的.
提交(Commit)事務. ?若事務成功執行, 對數據庫的更改變得可見.
若其中一個查詢失敗, ?整個事務被回滾(rolle back).
上面的流程可以使用下面的代碼來執行:
$transaction = $connection->beginTransaction ( ) ;
try
{
? ? $connection->createCommand( $sql1 ) ->execute ( ) ;
? ? $connection->createCommand( $sql2 ) ->execute ( ) ;
? ? //.... other SQL executions
? ? $transaction ->commit( ) ;
}
catch ( Exception ?$e) ?// an exception is raised if a query fails
{
? ? $transaction ->rollBack( ) ;
}
AR中使用方法:
每個 AR 實例都含有一個屬性名叫 dbConnection ,是一個 CDbConnection 的實例,這樣我們可以在需要時配合 AR 使用由 Yii DAO 提供的 事務 功能:
$model=Post::model();
$transaction=$model->dbConnection->beginTransaction();
try
{
? ? // 查找和保存是可能由另一個請求干預的兩個步驟
? ? // 這樣我們使用一個事務以確保其一致性和完整性
? ? $post=$model->findByPk(10);
? ? $post->title='new post title';
? ? $post->save();
? ? $transaction->commit();
}
catch(Exception $e)
{
? ? $transaction->rollBack();
}
注意:上面紅色部分其實都是CDbconnection的實例
原文地址:http://hnlixf.iteye.com/blog/1560116
原文地址:http://blog.csdn.net/ajaxchen_615/article/details/6973922
總結
以上是生活随笔為你收集整理的Yii 1.0 数据库操作 增、删、改、查 、对象转数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SNV(standard Normal
- 下一篇: 免费分享kali-linux-2019.