Yii的增删改查

2014-9-15 liyangweb.com 李杨 PHP

 如果英文不错,可以直接看原文地址http://www.yiiframework.com/doc/guide/1.1/en/database.ar 


 对于一个Model Post 有如下的4中查询方法,返回对象或者对象数组。

 // find the first row satisfying the specified condition

$post=Post::model()->find($condition,$params);
// find the row with the specified primary key
$post=Post::model()->findByPk($postID,$condition,$params);
// find the row with the specified attribute values
$post=Post::model()->findByAttributes($attributes,$condition,$params);
// find the first row using the specified SQL statement
$post=Post::model()->findBySql($sql,$params);

 

假设我们查询postID = 10的数据,怎么查询呢,见下面

 // find the row with postID=10

$post=Post::model()->find('postID=:postID', array(':postID'=>10));

条件$condition 就是我们sql里的where部分,那参数怎么办呢,通过params传递,不过名字是加了":"的。

 

YII有个CDbCriteria类来构造查询,如果我们查询postId为10的title,CdbCriteria是这样构造的

$criteria=new CDbCriteria;
$criteria->select='title';  // only select the 'title' column
$criteria->condition='postID=:postID';
$criteria->params=array(':postID'=>10);

$post=Post::model()->find($criteria); // $params is not needed 

 

 你也可以写成下面这样

$post=Post::model()->find(array(
    
'select'=>'title',
    
'condition'=>'postID=:postID',
    
'params'=>array(':postID'=>10),

)); 

 

findByAttributes 里的

$attributes就是字段的名字.

 

查询title为abc怎么查询呢?见下面

Post::model()->findByAttributes(array('title'=>'abc'))

 

 其它方法:

 

1、$admin=Admin::model()->findAll($condition,$params);    
 
该方法是根据一个条件查询一个集合,如: 
findAll("username=:name",array(":name"=>$username));    
 
 
2、$admin=Admin::model()->findAllByPk($postIDs,$condition,$params); 
findAllByPk($id,"name like ':name' and age=:age" ,array(':name'=>$name,'age'=>$age));    
 
该方法是根据主键查询一个集合,可以使用多个主键,如: 
findAllByPk(array(1,2)); 
     
 
3、$admin=Admin::model()->findAllByAttributes($attributes,$condition,$params); 
 
该方法是根据条件查询一个集合,可以是多个条件,把条件放到数组里面,如: 
findAllByAttributes(array('username'=>'admin')); 
 
 
4、$admin=Admin::model()->findAllBySql($sql,$params); 
 
该方法是根据SQL语句查询一个数组,如: 
findAllBySql("select *from admin where username=:name",array(':name'=>'admin')); 
----------------------------------------------------------------------------- 
二、查询对像的方法 
1、$admin=Admin::model()->findByPk($postID,$condition,$params); 
 
根据主键查询出一个对象,如:findByPk(1); 
 
2、$row=Admin::model()->find($condition,$params); 
 
根据一个条件查询出一组数据,可能是多个,但是他只返回第一行数据,如: 
find('username=:name',array(':name'=>'admin')); 
 
3、$admin=Admin::model()->findByAttributes($attributes,$condition,$params); 
 
该方法是根据条件查询一组数据,可以是多个条件,把条件放到数组里面,他查询的也是第一条数据,如: 
findByAttributes(array('username'=>'admin')); 
 
 
4、$admin=Admin::model()->findBySql($sql,$params); 
 
该方法是根据SQL语句查询一组数据,他查询的也是第一条数据,如: 
findBySql("select *from admin where username=:name",array(':name'=>'admin')); 
 
5、拼一个获得SQL的方法,在根据find查询出一个对象 
$criteria=new CDbCriteria; 
$criteria->select='username';  // only select the 'title' column 
$criteria->condition='username=:username'; 
$criteria->params=array(':username=>'admin'); 
$post=Post::model()->find($criteria); // $params is not needed 
 
 
------------------------------------------------------------------------------ 
三、查询个数,判断查询是否有结果 
1、$n=Post::model()->count($condition,$params); 
 
该方法是根据一个条件查询一个集合有多少条记录,返回一个int型数字,如 
count("username=:name",array(":name"=>$username));    
 
2、$n=Post::model()->countBySql($sql,$params); 
 
该方法是根据SQL语句查询一个集合有多少条记录,返回一个int型数字,如 
countBySql("select *from admin where username=:name",array(':name'=>'admin')); 
 
3、$exists=Post::model()->exists($condition,$params); 
 
该方法是根据一个条件查询查询得到的数组有没有数据,如果有数据返回一个true,否则没有找到 
 
 
================================================================================================================= 
四、添加的方法 
$admin=new Admin;      
$admin->username=$username; 
$admin->password=$password; 
if($admin->save()>0){ 
  echo "添加成功"; 
}else{ 
  echo "添加失败"; 
==================================================================================================================== 
五、修改的方法 
1、Post::model()->updateAll($attributes,$condition,$params); 
 
$count = Admin::model()->updateAll(array('username'=>'11111','password'=>'11111'),'password=:pass',array(':pass'=>'1111a1')); 
if($count>0){ 
  echo "修改成功"; 
}else{ 
  echo "修改失败"; 
 
2、Post::model()->updateByPk($pk,$attributes,$condition,$params); 
 
$count = Admin::model()->updateByPk(1,array('username'=>'admin','password'=>'admin')); 
$count = Admin::model()->updateByPk(array(1,2),array('username'=>'admin','password'=>'admin'),'username=:name',array(':name'=>'admin')); 
if($count>0){ 
  echo "修改成功"; 
}else{ 
  echo "修改失败"; 
$pk代表主键,可以是一个也可以是一个集合,$attributes代表是要修改的字段的集合,$condition代表条件,$params传入的值 
 
3、Post::model()->updateCounters($counters,$condition,$params); 
 
$count =Admin::model()->updateCounters(array('status'=>1),'username=:name',array(':name'=>'admin')); 
if($count>0){ 
  echo "修改成功"; 
}else{ 
  echo "修改失败"; 
array('status'=>1)代表数据库中的admin表根据条件username='admin',查询出的所有结果status字段都自加1 
 
================================================================================================================================================ 
六、删除的方法 
1、Post::model()->deleteAll($condition,$params); 
 
$count = Admin::model()->deleteAll('username=:name and password=:pass',array(':name'=>'admin',':pass'=>'admin')); 
      $id=1,2,3 
      deleteAll('id in(".$id.")');删除id为这些的数据 
if($count>0){ 
  echo "删除成功"; 
}else{ 
  echo "删除失败"; 
 
2、Post::model()->deleteByPk($pk,$condition,$params); 
$count = Admin::model()->deleteByPk(1); 
$count = Admin::model()->deleteByPk(array(1,2),'username=:name',array(':name'=>'admin')); 
if($count>0){ 
  echo "删除成功"; 
}else{ 
  echo "删除失败"; 
}

标签: Yii

评论:

annomaplexel
2019-02-09 03:01
<a href="http://www.daddeaze.com/hombres-nike-free-flyknit-4.0-oro-verde-kurpesb">hombres nike free flyknit 4.0 oro verde</a> <a href="http://www.debracousins.com/women-jordans-fight-origin-zapatost">women jordans fight origin</a> <a href="http://www.yankaripark.com/converse-femme-all-star-blanche-shoesz">converse femme all star blanche</a> <a href="http://www.yicailottery.com/nike-air-max-zero-bon-march%C3%A9-years-schuheb">nike air max zero bon march茅 years</a> <a href="http://www.calebcraw.com/red-sox-26-wade-boggs-cream-sawyer-hooded-sweatshirt-mlb-hoodie-nflu">red sox 26 wade boggs cream sawyer hooded sweatshirt mlb hoodie</a> <a href="http://www.liquidputter.com/nike-zoom-structure-1-skou">nike zoom structure 1</a>
annomaplexel http://www.annomaplexel.com/
attawhed
2019-01-25 06:36
<a href="http://www.publiswiss.net/nike-structure-18-lilla-guy-obuve">nike structure 18 lilla guy</a> <a href="http://www.puffyp.net/nike-air-max-tailwind-7-kvinders-hvid-lilla-butya">nike air max tailwind 7 kvinders hvid lilla</a> <a href="http://www.radiosbestfriend.net/nike-magista-cleats-amarillo-verde-butya">nike magista cleats amarillo verde</a> <a href="http://www.relaxmassagestudio.net/dam%C3%A4nner-nike-cortez-rot-gold-obuve">dam盲nner nike cortez rot gold</a> <a href="http://www.risaralda.net/nike-kobe-5-jaune-vert-scarped">nike kobe 5 jaune vert</a> <a href="http://www.santfeliucentre.net/nike-kd-9-nero-volume-schuhef">nike kd 9 nero volume</a>
attawhed http://www.attawhed.net/
trafassi
2019-01-07 01:34
<a href="http://www.emmamoney.com/lunarglide-7-billig-internet-schuhec">lunarglide 7 billig internet</a> <a href="http://www.guntruthers.com/limited-nike-camo-womens-vonn-bell-jersey-nfl-24-new-orleans-saints-rush-realtree-nflr">limited nike camo womens vonn bell jersey nfl 24 new orleans saints rush realtree</a> <a href="http://www.jayandarmando.com/nfl-nike-buffalo-bills-11-zay-jones-royal-blue-backer-pullover-hoodie-nflx">nfl nike buffalo bills 11 zay jones royal blue backer pullover hoodie</a> <a href="http://www.mikevi.com/nike-free-5.0-wei%C3%9F-volt-schuheg">nike free 5.0 wei脽 volt</a> <a href="http://www.mynaturalogy.com/nike-free-run-4.0-v3-blanco-key-scarpeg">nike free run 4.0 v3 blanco key</a> <a href="http://www.wvusigmakappa.com/nike-free-connect-kvinners-sko-kurpesf">nike free connect kvinners sko</a>
trafassi http://www.trafassi.com/
kinkfresno
2019-01-03 13:12
<a href="http://www.shoutwithus.com/air-max-90-blue-man-shoesc">air max 90 blue man</a> <a href="http://www.leviandval.com/nike-roshe-run-black-marble-american-flag-pride-custom-skog">nike roshe run black marble american flag pride custom</a> <a href="http://www.buysfohomes.com/roshe-run-nebula-custom-painted-sportsf">roshe run nebula custom painted</a> <a href="http://www.canusapos.com/dsm-air-jordan-1-flight-club-runningd">dsm air jordan 1 flight club</a> <a href="http://www.moveinplace.com/nike-minnesota-vikings-12-percy-harvin-purple-limited-jersey-nflc">nike minnesota vikings 12 percy harvin purple limited jersey</a> <a href="http://www.thecreditgods.com/billig-nike-huarache-ultra-dam%C3%A4nner-lila-skoa">billig nike huarache ultra dam盲nner lila</a>
kinkfresno http://www.kinkfresno.com/
clubcombo
2019-01-02 15:32
<a href="http://www.cosmonet.net/jordan-1-orion-bleu-schuhea">jordan 1 orion bleu</a> <a href="http://www.cpgjoblist.net/nike-free-run-5.0-r%C3%B8d-zombies-kurpese">nike free run 5.0 r酶d zombies</a> <a href="http://www.crosswindschurch.net/kvinners-nike-flyknit-agility-beige-chaussuresa">kvinners nike flyknit agility beige</a> <a href="http://www.cuttingedgeoffers.net/nike-air-max-1-ultra-moire-femmes-wolf-gris-kurpesg">nike air max 1 ultra moire femmes wolf gris</a> <a href="http://www.cvceurope.net/kobe-8-arancia-schuhee">kobe 8 arancia</a> <a href="http://www.cyberlec.net/air-max-95-rosso-nero-bianca-obuvg">air max 95 rosso nero bianca</a>
clubcombo http://www.clubcombo.net/
bundlemurah
2019-01-02 08:26
<a href="http://www.kellyalberto.com/nike-kaishi-lightweight-zapatilla-de-deporte-mujeres-boot-scarpeg">nike kaishi lightweight zapatilla de deporte mujeres boot</a> <a href="http://www.kscfoundation.com/adidas-yeezy-boost-350-rosso-viola-kurpesf">adidas yeezy boost 350 rosso viola</a> <a href="http://www.moorefornc.com/air-jordan-4-viola-and-nero-schuheg">air jordan 4 viola and nero</a> <a href="http://www.segalino.com/adidas-forum-mid-blanco-rojo-vertical-schuheb">adidas forum mid blanco rojo vertical</a> <a href="http://www.callalabaynsw.com/nike-stefan-janoski-max-schwarz-mesh-chaussurese">nike stefan janoski max schwarz mesh</a> <a href="http://www.clcohelp.com/herre-nike-free-6.0-lyser%C3%B8d-guld-butyf">herre nike free 6.0 lyser酶d guld</a>
bundlemurah http://www.bundlemurah.com/
cv9uzx13
2018-12-31 01:11
<a href="http://www.72y9pzek.com/nike-air-max-90-off-blanc-or-butye">nike air max 90 off blanc or</a> <a href="http://www.ata4l20x.com/air-jordan-retro-12-kvinders-s%C3%B8lv-gr%C3%A5-schuhea">air jordan retro 12 kvinders s酶lv gr氓</a> <a href="http://www.avoqyd09.com/acheter-nike-air-force-1-foamposite-online-chaussuresa">acheter nike air force 1 foamposite online</a> <a href="http://www.ds432gxe.com/nike-blazer-mid-premium-blu-dusk-obuva">nike blazer mid premium blu dusk</a> <a href="http://www.6mohycx0.com/nike-air-max-90-svart-and-gr%C3%A5-queen-butyd">nike air max 90 svart and gr氓 queen</a> <a href="http://www.rnokcrc1.com/nike-shox-current-negro-xray-scarpec">nike shox current negro xray</a>
cv9uzx13 http://www.cv9uzx13.com/
sparktheword
2018-12-29 08:27
<a href="http://www.masterelief.com/nike-free-4.0-flyknit-maschio-trainers-butye">nike free 4.0 flyknit maschio trainers</a> <a href="http://www.nwlcenter.com/nike-flyknit-racer-triple-noir-pre-order-obuve">nike flyknit racer triple noir pre order</a> <a href="http://www.piezoinjector.com/nike-hyperfuse-viola-obuvd">nike hyperfuse viola</a> <a href="http://www.printonlipro.com/huarache-utility-rojo-and-negro-mold-kurpesg">huarache utility rojo and negro mold</a> <a href="http://www.biagricola.com/nike-air-max-95-rojo-gris-obuvb">nike air max 95 rojo gris</a> <a href="http://www.dennygorman.com/dam%C3%A4nner-asics-gel-hyper-33-rot-rosa-butya">dam盲nner asics gel hyper 33 rot rosa</a>
sparktheword http://www.sparktheword.com/
daftarkursus
2018-12-28 19:45
<a href="http://www.geuwompo.com/nike-free-run-womens-america-skob">nike free run womens america</a> <a href="http://www.partyhubuk.com/adidas-superstar-2-light-blau-shoesv">adidas superstar 2 light blau</a> <a href="http://www.shahsmkj.com/adidas-tubular-runner-dam%C3%A4nner-rot-runninga">adidas tubular runner dam盲nner rot</a> <a href="http://www.wanbilm.com/ray-ban-justin-classic-rb4165-sunglassesr">ray ban justin classic rb4165</a> <a href="http://www.dmmsband.com/reebok-gl-6000-white-shoesv">reebok gl 6000 white</a> <a href="http://www.playhousecash.com/nike-air-zoom-pegasus-92-skow">nike air zoom pegasus 92</a>
daftarkursus http://www.daftarkursus.com/
bidmani
2018-12-27 20:24
<a href="http://www.feelsafeinc.com/dam%C3%A4nner-flyknit-lunar-1-schuhed">dam盲nner flyknit lunar 1</a> <a href="http://www.gaeconomics.com/nike-magista-cleats-argento-marrone-scarpea">nike magista cleats argento marrone</a> <a href="http://www.garagesetcinc.com/lebron-13-blau-and-wei%C3%9F-noise-kurpesf">lebron 13 blau and wei脽 noise</a> <a href="http://www.paleofasting.com/nfl-joe-flacco-youth-limited-purple-jersey-5-baltimore-ravens-nike-therma-long-sleeve-nflr">nfl joe flacco youth limited purple jersey 5 baltimore ravens nike therma long sleeve</a> <a href="http://www.revarepair.com/adidas-pr%C3%B8dator-instinct-bl%C3%A5-2014-kurpesf">adidas pr酶dator instinct bl氓 2014</a> <a href="http://www.saraviquez.com/adidas-ultra-boost-alle-sort-herre-loafers-schuhef">adidas ultra boost alle sort herre loafers</a>
[url=http://www.bidmani.com/]bidmani[/url]
akissilindir
2018-12-27 15:06
<a href="http://www.wtaarchitects.com/dortmund-9-yarmolenko-away-long-sleeves-soccer-club-jersey-nflu">dortmund 9 yarmolenko away long sleeves soccer club jersey</a> <a href="http://www.bibleofpeace.com/mujeres-air-max-1-pinnacle-kurpesb">mujeres air max 1 pinnacle</a> <a href="http://www.thepinpress.com/nike-flyknit-lunar-1-menn-r%C3%B8d-schuhec">nike flyknit lunar 1 menn r酶d</a> <a href="http://www.fhnconference.com/nike-flyknit-trainer-r%C3%B8d-queen-schuheg">nike flyknit trainer r酶d queen</a> <a href="http://www.haerinonghyup.com/air-max-95-triple-schwarz-uk-kurpesd">air max 95 triple schwarz uk</a> <a href="http://www.burkkinc.com/air-jordan-dress-scarpe-obuvg">air jordan dress scarpe</a>
akissilindir http://www.akissilindir.com/

发表评论:

Powered by emlog 冀ICP备13011830号-1