首页 > 开发 > Php > 正文

Yii基于数组和对象的Model查询技巧实例详解

2020-02-18 23:01:28
字体:
来源:转载
供稿:网友

本文实例讲述了Yii基于数组和对象的Model查询技巧。分享给大家供大家参考,具体如下:

对于一个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);//未找到返回null//通过指定的SQL 语句查找结果中的第一行 find the first row using the specified SQL statement$post=Post::model()->findBySql($sql,$params);

如果find 方法找到了一个满足查询条件的行,它将返回一个Post 实例,实例的属性含有数据表行中相应列的值。然后我们就可以像读取普通对象的属性那样读取载入的值,例如echo $post->title;。如果使用给定的查询条件在数据库中没有找到任何东西, find 方法将返回null。

调用find 时,我们使用$condition 和$params 指定查询条件。此处$condition 可以是SQL 语句中的WHERE 字符串,$params 则是一个参数数组,其中的值应绑定到$condation 中的占位符。例如:假设我们查询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

一种替代CDbCriteria 的方法是给find 方法传递一个数组。数组的键和值各自对应标准( criterion)的属性名和值,上面的例子可以重写为如下:

$post=Post::model()->find(array(  'select'=>'title',  'condition'=>'postID=:postID',  'params'=>array(':postID'=>10),));

当然也适用于findAll()

self::$_items[$type]=array();$models=self::model()->findAll(array(  'condition'=>'type=:type',  'params'=>array(':type'=>$type),  'order'=>'position',));

当一个查询条件是关于按指定的值匹配几个列时,我们可以使用findByAttributes()。我们使$attributes 参数是一个以列名做索引的值的数组。
findByAttributes 里的$attributes就是字段的名字.查询title为abc怎么查询呢?见下面

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表