Yii操作数据库的3种方法

yipeiwu_com5年前PHP代码库
一、执行原生太SQL的PDO方式。
复制代码 代码如下:
$sql = "";//原生态sql语句
xx::model()->dbConnection->createCommand($sql)->execute();

二、Active Record方式
(1)New 方式
复制代码 代码如下:
$post=new Post;
$post->title='sample post';
$post->content='post body content';
$post->save();

(2)Criteria方式
也可以使用 $condition 指定更复杂的查询条件。 不使用字符串,我们可以让 $condition 成为一个 CDbCriteria 的实例,它允许我们指定不限于 WHERE 的条件。
复制代码 代码如下:
$criteria=new CDbCriteria;
$criteria->select='title';  // 只选择 'title' 列
$criteria->condition='postID=:postID';
$criteria->params=array(':postID'=>10);
$post=Post::model()->find($criteria);

一种替代 CDbCriteria 的方法是给 find 方法传递一个数组。 数组的键和值各自对应标准(criterion)的属性名和值,上面的例子可以重写为如下:
复制代码 代码如下:
$post=Post::model()->find(array(
    'select'=>'title',
    'condition'=>'postID=:postID',
    'params'=>array(':postID'=>10),
));

当一个查询条件是关于按指定的值匹配几个列时,我们可以使用 findByAttributes()。我们使 $attributes 参数是一个以列名做索引的值的数组。在一些框架中,此任务可以通过调用类似 findByNameAndTitle 的方法实现。虽然此方法看起来很诱人,但它常常引起混淆、冲突和比如列名大小写敏感的问题。
三、Query Builder 方式
复制代码 代码如下:
$user = Yii::app()->db->createCommand()
    ->select('id, username, profile')
    ->from('tbl_user u')
    ->join('tbl_profile p', 'u.id=p.user_id')
    ->where('id=:id', array(':id'=>$id))
    ->queryRow();

相关文章

php print EOF实现方法

我写段php代码如下: 复制代码 代码如下:<? if(test case) print<<<EOT <....html code....> EOF;...

php优化及高效提速问题的实现方法第1/2页

一、 在函数中,传递数组时使用 return 比使用 global 要高效,比如: function userloginfo($usertemp){ $detail=explode("|...

php实现检查文章是否被百度收录

php实现检查文章是否被百度收录

网站都有个后台,后台发表新闻与产品,发完后如果你要去查看该页面有没有被百度收录,还要通过第三方工具或直接去百度搜。最近在做SEO,每天都要查看前一天发的文章有没有被收录,就这个工作就是一...

详解php的魔术方法__get()和__set()使用介绍

先看看php官方文档的解释: __set() is run when writing data to inaccessible properties. __get() is utiliz...

Swoole 5将移除自动添加Event::wait()特性详解

前言 在之前的版本中,编写Cli命令行脚本中使用异步或协程功能时,Swoole会自动在脚本末尾检测是否有Event::wait()调用,如果没有,底层会自动调用register_shut...