yii数据库查询

Yii AR很好很强大,但刚开始不知道怎么使用

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

下面是我对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 ' ))

转自:http://www.cnblogs.com/likwo/archive/2011/09/01/2162017.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值