Yii操作数据库的3种方法_PHP

WBOY
Release: 2016-06-01 11:55:26
Original
865 people have browsed it

一、执行原生太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();

Related labels:
yii
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!