Yii AR很好很强大,但刚开始不知道怎么使用
如果英文不错,可以直接看原文地址http://www.yiiframework.com/doc/guide/1.1/en/database.ar
下面是我对AR的一些理解
$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 );
//
$post = Post :: model() -> findByPk( $postID , $condition , $params );
//
$post = Post :: model() -> findByAttributes( $attributes , $condition , $params );
//
$post = Post :: model() -> findBySql( $sql , $params );
假设我们查询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);
$criteria -> select = ' title ' ;
$criteria -> condition = ' postID=:postID ' ;
$criteria -> params = array ( ' :postID ' => 10);
$post=Post::model()->find($criteria);
$post
=
Post
::
model()
->
find(
array
(
'
select
'
=>
'
title
'
,
'
condition
'
=>
'
postID=:postID
'
,
'
params
'
=>
array
(
'
:postID
'
=>
10
)
,
));
findByAttributes
查询title为abc怎么查询呢?见下面
Post
::
model()
->
findByAttributes(
array
(
'
title
'
=>
'
abc
'
))
转自:http://www.cnblogs.com/likwo/archive/2011/09/01/2162017.html
转自:http://www.cnblogs.com/likwo/archive/2011/09/01/2162017.html