查:
例一:
$connection = \yii::$app->db; //you have to define db connection in config/main.php
$queryEmailSql = "select email from user";
$allEmail = $connection->createCommand($queryEmailSql)->queryAll();
例二:(说明:把查询条件作为参数,比较安全,可直接避免注入。要是直接用在SQL语句中,最好要经过防注入处理。)
$db = Yii::app()->db; //you have to define db connection in config/main.php
$sql = "select sum(if(starttime>‘09:00:00‘,1,0)) as late,
sum(if(endtime<‘18:00:00‘,1,0)) as early
from present where userid=:userid and date between :date_start and :date_end"
$results = $db->createCommand($sql)->query(array(
‘:userid‘ => 115,‘:date_start‘=>‘2009-12-1‘,‘:date_end‘=>‘2009-12-31‘,
));
foreach($results as $result){
echo $result[‘late‘]," and ",$result[‘early‘]," /n";
}
等同于
$sql = "select sum(if(starttime>‘09:00:00‘,1,0)) as late,
sum(if(endtime<‘18:00:00‘,1,0)) as early
from present where userid=115 and date between ‘2009-12-1‘ and ‘2009-12-31‘"
$results = $db->createCommand($sql)->query();
foreach($results as $result){
echo $result[‘late‘]," and ",$result[‘early‘]," /n";
}
//1.该方法是根据一个条件查询一个集合
$admin
=Admin::model()->findAll(
$condition
,
$params
);
$admin
=Admin::model()->findAll(
"username=:name"
,
array
(
":name"
=>
$username
));
//2. findAllByPk(该方法是根据主键查询一个集合,可以使用多个主键)
$admin
=Admin::model()->findAllByPk(
$postIDs
,
$condition
,
$params
);
$admin
=Admin::model()->findAllByPk(
$id
,
"name like :name and age=:age"
,
array
(
‘:name‘
=>
$name
,
‘age‘
=>
$age
));
$admin
=Admin::model()->findAllByPk(
array
(1,2));//????
//3.findAllByAttributes (该方法是根据条件查询一个集合,可以是多个条件,把条件放到数组里面)
$admin
=Admin::model()->findAllByAttributes(
$attributes
,
$condition
,
$params
);
$admin
=Admin::model()->findAllByAttributes(
array
(
‘username‘
=>
‘admin‘
));
//4.findAllBySql (该方法是根据SQL语句查询一个数组)
$admin
=Admin::model()->findAllBySql(
$sql
,
$params
);
$admin
=Admin::model()->findAllBySql(
"select * from admin where username like :name"
,
array
(
‘:name‘
=>
‘yang%‘
));
//拼一个获得SQL的方法,在根据find查询出一个对象
$criteria
=
new
CDbCriteria;
$criteria
->select=
‘username‘
;
// only select the ‘username‘ column
$criteria
->condition=
‘username=:username‘
;
$criteria
->params=
array
(
":username=>‘admin‘"
);
$criteria
->order =
"id DESC"
;
$criteria
->limit =
"3"
;
$post
=Post::model()->find(
$criteria
);
// $params isnot needed
查询个数,判断查询是否有结果
//该方法是根据一个条件查询一个集合有多少条记录,返回一个int型数字
$n
=Post::model()->
count
(
$condition
,
$params
);
$n
=Post::model()->
count
(
"username=:name"
,
array
(
":name"
=>
$username
));
//该方法是根据SQL语句查询一个集合有多少条记录,返回一个int型数字
$n
=Post::model()->countBySql(
$sql
,
$params
);
$n
=Post::model()->countBySql(
"select * from admin where username=:name"
,
array
(
‘:name‘
=>
‘admin‘
));
//该方法是根据一个条件查询查询得到的数组有没有数据,如果有数据返回一个true,否则没有找到
$exists
=Post::model()->exists(
$condition
,
$params
);
$exists
=Post::model()->exists(
"name=:name"
,
array
(
":name"
=>
$username
));
$admin=Admin::model()->findBySql ($sql,$params);
该方法是根据SQL语句查询一组数据,他查询的也是第一条数据,如:
findBySql("select *from admin where username=:name",array(‘:name‘=>‘admin‘));
// 取回所有活跃客户(状态为 *active* 的客户)并以他们的 ID 排序:
$customers
= Customer::find()
->where([
‘status‘
=> Customer::STATUS_ACTIVE])
->orderBy(
‘id‘
)
->all();
// 返回ID为1的客户:
$customer
= Customer::find()
->where([
‘id‘
=> 1])
->one();
// 取回活跃客户的数量:
$count
= Customer::find()
->where([
‘status‘
=> Customer::STATUS_ACTIVE])
->
count
();
// 以客户ID索引结果集:
$customers
= Customer::find()->indexBy(
‘id‘
)->all();
// $customers 数组以 ID 为索引
// 用原生 SQL 语句检索客户:
$sql
=
‘SELECT * FROM customer‘
;
$customers
= Customer::findBySql(
$sql
)->all();
// 返回 id 为 1 的客户
$customer
= Customer::findOne(1);
// 返回 id 为 1 且状态为 *active* 的客户
$customer
= Customer::findOne([
‘id‘
=> 1,
‘status‘
=> Customer::STATUS_ACTIVE,
]);
// 返回id为1、2、3的一组客户
$customers
= Customer::findAll([1, 2, 3]);
// 返回所有状态为 "deleted" 的客户
$customer
= Customer::findAll([
‘status‘
=> Customer::STATUS_DELETED,
]);
// 以数组而不是对象形式取回客户信息:
$customers
= Customer::find()
->asArray()
->all();
// $customers 的每个元素都是键值对数组
// 一次提取 10 个客户信息
foreach
(Customer::find()->batch(10)
as
$customers
) {
// $customers 是 10 个或更少的客户对象的数组
}
// 一次提取 10 个客户并一个一个地遍历处理
foreach
(Customer::find()->each(10)
as
$customer
) {
// $customer 是一个 ”Customer“ 对象
}
// 贪婪加载模式的批处理查询
foreach
(Customer::find()->with(
‘orders‘
)->each()
as
$customer
) {
}
http://www.yiifans.com/yii2/guide/db-active-record.html
User::find()->all(); 此方法返回所有数据; User::findOne($id); 此方法返回 主键 id=1 的一条数据(举个例子); User::find()->where([‘name‘ => ‘小伙儿‘])->one(); 此方法返回 [‘name‘ => ‘小伙儿‘] 的一条数据; User::find()->where([‘name‘ => ‘小伙儿‘])->all(); 此方法返回 [‘name‘ => ‘小伙儿‘] 的所有数据; User::find()->orderBy(‘id DESC‘)->all(); 此方法是排序查询; User::findBySql(‘SELECT * FROM user‘)->all(); 此方法是用 sql 语句查询 user 表里面的所有数据; User::findBySql(‘SELECT * FROM user‘)->one(); 此方法是用 sql 语句查询 user 表里面的一条数据; User::find()->andWhere([‘sex‘ => ‘男‘, ‘age‘ => ‘24‘])->count(‘id‘); 统计符合条件的总条数; User::find()->one(); 此方法返回一条数据; User::find()->all(); 此方法返回所有数据; User::find()->count(); 此方法返回记录的数量; User::find()->average(); 此方法返回指定列的平均值; User::find()->min(); 此方法返回指定列的最小值 ; User::find()->max(); 此方法返回指定列的最大值 ; User::find()->scalar(); 此方法返回值的第一行第一列的查询结果; User::find()->column(); 此方法返回查询结果中的第一列的值; User::find()->exists(); 此方法返回一个值指示是否包含查询结果的数据行; User::find()->batch(10); 每次取 10 条数据 User::find()->each(10); 每次取 10 条数据, 迭代查询
User::find()->select([‘id‘,‘name‘,‘author‘])->where([‘in‘,‘id‘,$ids])->asArray()->all();
增:
方法一:
$applyres = $connection->createCommand()->insert(‘user‘,[‘email‘=>$email, ‘name‘=>$name, ‘mobile‘=>$phone, ‘status‘=>$status,‘create_time‘=>time(), ‘is_super‘=>0, ‘password‘=>new Expression(‘PASSWORD(:p)‘,[‘:p‘=>$password]), ‘remark‘=>$disc])->execute();//成功返回1,否则返回0
方法二:
$admin
=
new
Admin;
$admin
->username =
$username
;
$admin
->password =
$password
;
$admin
->save();
if
(
$admin
->save()
> 0){
echo
"添加成功"
;
$id = $admin->attributes[‘id‘];//返回刚才插入的那条数据的id
}
else
{
echo
"添加失败"
; }
修改
//update user set mobile=‘{$phone}‘,remark=‘{$remark}‘ where email=‘{$email}‘;
$count =User::updateAll(array(‘mobile‘=>$phone,‘remark‘=>$remark),‘email=:email‘,array(‘:email‘=>$email));
//第一个参数是$attributes,第二个参数是$conditions,第三个参数是条件的的值$param
或者用createCommand()的方式
Post::model()->updateAll(
$attributes
,
$condition
,
$params
);
$count
=Admin::model()->updateAll(
array
(
‘username‘
=>
‘11111‘
,
‘password‘
=>
‘11111‘
),
‘password=:pass‘
,
array
(
‘:pass‘
=>
‘1111a1‘
));
//修改
password为1111a1的username=1111 and password=11111
if
(
$count
> 0){
echo
"修改成功"
; }
else
{
echo
"修改失败"
; }
$res = User::updateAll([‘status‘=>3],‘id=:id‘,[‘:id‘=>$userId]);//修改id为$userId的status为3
//$pk主键,可以是一个也可以是一个集合,$attributes是要修改的字段的集合,$condition条件,$params传入的值
Post::model()->updateByPk(
$pk
,
$attributes
,
$condition
,
$params
);
$count
=Admin::model()->updateByPk(1,
array
(
‘username‘
=>
‘admin‘
,
‘password‘
=>
‘admin‘
));//修改主键为1的用户名为admin密码为admin
$count
=Admin::model()->updateByPk(1
,
array
(
‘username‘=>‘admin
‘
,
‘password‘=>‘admin
‘
),‘username=:name and password:psw‘,
array
(
‘:name‘
=>
‘commonuser‘,
‘:psw‘=>‘compassword‘
));//修改主键为1且username=commonuser,password=compassword那条记录的username为admin,password为admin
if
(
$count
>0){
echo
"修改成功"
; }
else
{
echo
"修改失败"
; }
Post::model()->updateCounters(
$counters
,
$condition
,
$params
);
$count
=Admin::model()->updateCounters(
array
(
‘status‘
=>1),
‘username=:name‘
,
array
(
‘:name‘
=>
‘admin‘
));
//array(‘status‘=>1)代表数据库中的post表根据条件username=‘admin‘,查询出的所有结果status字段都自加1
if
(
$count
> 0){
echo
"修改成功"
; }
else
{
echo
"修改失败"
; }
$userLimitRet = UserLimit::model()->findByPk (array (‘user_id‘ => $userId, ‘category_id‘ => $v));
$userLimitRet->order = $order;
if (! $userLimitRet->update ()) {
}
$userAmount=userAmount::model()->findByPk ($userId);
$userAmount->credit=Yii::app()->request->getParam(‘credit‘,10000);
$ret = $userAmount->save ();
若要查看sql语句可在execute之前执行getRawSql()
$connection->createCommand()->insert(‘user‘, [‘email‘ => $email, ‘name‘ => $name, ‘mobile‘ => $phone, ‘status‘ => $status, ‘create_time‘ => time(), ‘is_super‘ => 0, ‘password‘ => new Expression(‘PASSWORD(:p)‘, [‘:p‘ => $password]), ‘remark‘ => $disc])->getRawSql();
删除:
//deleteAll
Post::model()->deleteAll(
$condition
,
$params
);
$count
= Admin::model()->deleteAll(
‘username=:name and password=:pass‘
,
array
(
‘:name‘
=>
‘admin‘
,
‘:pass‘
=>
‘admin‘
));
$count
= Admin::model()->deleteAll(
‘id in("1,2,3")‘
);
//删除id为这些的数据
if
(
$count
>0){
echo
"删除成功"
; }
else
{
echo
"删除失败"
; }
//deleteByPk
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
"删除失败"
; }
$connection->createCommand()->delete(‘user‘, ‘id = :userid and email=:email‘, [‘:userid‘=>$userid, ‘:email‘=>444])->execute();//打印出的语句DELETE FROM `user` WHERE id = ‘124‘ and email=444
其他:
事务
$db = Yii::app()->db;
$dbTrans = $db->beginTransaction();
$dbTrans->commit();
$dbTrans->rollback();
//事务的基本结构(多表更新插入操作请使用事务处理)
$dbTrans
= Yii::app()->db->beginTransaction();
try
{
$post
=
new
Post;
$post
->
‘title‘
=
‘Hello dodobook!!!‘
;
if
(!
$post
->save())
throw
new
Exception(
"Error Processing Request"
, 1);
$dbTrans
->commit();
// $this->_end(0,‘添加成功!!!‘);
}
catch
(Exception
$e
){
$dbTrans
->rollback();
// $this->_end($e->getCode(),$e->getMessage());
}
YII2中where函数讲解
在Yii的Model里进行查询的时候 where是必不可少的。
Where方法声明为
复制代码
其中参数 $condition类型为字符串或者数组
1、字符串
字符串是最简单的,直接按sql中的where条件写就可以,如
复制代码
2、数组
如果是数组的情况下,有两种格式的写法。
复制代码
如果value值是数组,那么会生成sql 中的IN语句;
复制代码
如果value值为Null,那么会生成 Is Null语句。
复制代码
第二种写法会根据不同的操作符生成不同的sql条件。
复制代码
如果某个运算数也是数组,那么会按如下格式转换为字符串,如
复制代码
注意:这个方法不会对进行引用或者编码操作。
复制代码
复制代码
注意:这个方法会对列进行引用,对数组中的值也会编码。
复制代码
如果值是数组的话,会生成多个like语句,并用 AND来连接。如
复制代码
注意:这个方法会对列进行引用,对数组中的值也会编码。
有时候你可能需要自己来处理%,那么可以用第三个参数:
复制代码
参考:
http://www.yii-china.com/video/index.html
http://www.yii-china.com/tutorial/index.html?type=2
http://www.yiichina.com/doc/guide/2.0
原文:http://www.cnblogs.com/ryanlamp/p/5143809.html