手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆

yii with的排序

首页 > PHP >

Yii在自己的AR中实现了relations,于是我们可以利用relations实现一些left join或者其他join能做的事情,常见的大家都懂,什么 belongs_to,has_one,has_many,many_to_many之类的
但用的最多的,一般都是has_one,has_many,毕竟查关联数据这个最方便了。

于是我们就会Table::model()->with('a','b')->findAll($cdbcriteria);
这个时候,如果需要用到a或b的排序,就有点痛苦,直接在$cdbcriteria中写的话,往往会报字段不存在,因此可以尝试这样
1、直接在relations中,在写成a时,直接加入'order'=>'id DESC'之类的内容
2、在with()中写: with(array('a'=>array('order'=>'id DESC'),'b'))

这样是不是就很方便了呢?
当然上面的代码是通过:

PHP代码
  1. public function with()  
  2. {  
  3.     if(func_num_args()>0)  
  4.     {  
  5.         $with=func_get_args();  
  6.         if(is_array($with[0]))  // the parameter is given as an array  
  7.             $with=$with[0];  
  8.         if(!empty($with))  
  9.             $this->getDbCriteria()->mergeWith(array('with'=>$with));  
  10.     }  
  11.     return $this;  
  12. }  

看了这段代码就基本上了解用法了,手册里也说了:
Specifies which related objects should be eagerly loaded. This method takes variable number of parameters. Each parameter specifies the name of a relation or child-relation. For example,

// find all posts together with their author and comments
Post::model()->with('author','comments')->findAll();
// find all posts together with their author and the author's profile
Post::model()->with('author','author.profile')->findAll();
The relations should be declared in relations().

By default, the options specified in relations() will be used to do relational query. In order to customize the options on the fly, we should pass an array parameter to the with() method. The array keys are relation names, and the array values are the corresponding query options. For example,
Post::model()->with(array(
    'author'=>array('select'=>'id, name'),
    'comments'=>array('condition'=>'approved=1', 'order'=>'create_time'),
))->findAll();
所以,有时候看看手册还是很重要的。




本站采用创作共享版权协议, 要求署名、非商业和保持一致. 本站欢迎任何非商业应用的转载, 但须注明出自"易栈网-膘叔", 保留原始链接, 此外还必须标注原文标题和链接.

Tags: yii, with, cdbcriteria

« 上一篇 | 下一篇 »

只显示10条记录相关文章

常用网站的反向代理页[2013-09-28] (浏览: 66059, 评论: 10)
Yii CDbCriteria的常用方法 (浏览: 56341, 评论: 5)
将Yiiframework与JQuery easyUI整合使用 (浏览: 38198, 评论: 2)
Yii:relations update(self::STAT) (浏览: 33673, 评论: 0)
值得收藏的yii2的doc中关于db Query的说明 (浏览: 29237, 评论: 0)
Yii Demos 随想 (浏览: 28544, 评论: 3)
在Yii框架中使用Hprose或PHPRPC (浏览: 27555, 评论: 0)
Yii ClinkPager 郁闷 (浏览: 27276, 评论: 2)
Yiiframework(Yii框架)开发笔记:续四 (浏览: 26746, 评论: 3)
Yii 一行代码,为模块绑定子域名 (浏览: 26085, 评论: 0)

发表评论

评论内容 (必填):