<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/">
<channel>
<title>成刚网志 &amp;amp;&amp;amp; CBolg Application</title>
<link>http://www.chenggang.net</link>
<description><![CDATA[记录我的网事历程，架起沟通的桥梁！欢迎留言！
]]></description>
<lastBuildDate>Sun, 05 Feb 2012 11:14:25 +0800</lastBuildDate>
<copyright>Copyright &amp;copy; 2012 by CBolg Application.</copyright>
<language>zh-cn</language>
<pubDate>Thu, 23 Feb 2012 03:34:53 +0800</pubDate>
<item>
<title>Yii中优化ActiveRecord的relation model取值</title>
<summary><![CDATA[AcivRcd的lin定义相关的类，可以很方便的取到相应的值。 比如： cl U xnd CAcivRcd{ublic funcin lin(){un y(gu = y(lf::BELONGS_TO, Gu, gu_id),);}} 可以很通过$u-gu获取Gu的实例化类，但是问题随之而来，如果gu这个表很大，对应的字段很多，CAcivRcd在取值的时候会…]]></summary>
<description><![CDATA[<p>
	ActiveRecord的relations定义相关的类，可以很方便的取到相应的值。</p>
<p>
	比如：</p>
<pre class="brush:php;" title="code">
class User extends CActiveRecord
{
	public function relations()
	{
		return array(
			&#39;group&#39; =&gt; array(self::BELONGS_TO, &#39;Group&#39;, &#39;group_id&#39;),
		);
	}
}
</pre>
<p>
	可以很通过$user-&gt;group获取Group的实例化类，但是问题随之而来，如果group这个表很大，对应的字段很多，CActiveRecord在取值的时候会把这些值都取出来，可是往往我们需要的仅仅是其中的一两个字段而已，这就需要在with的时候设置select信息。</p>
<p>
	如果这样设置：</p>
<pre class="brush:php;" title="code">
$criteria = new CDbCriteria();
$criteria-&gt;distinct     = true;
$criteria-&gt;select = &quot; t.* &quot;;
$criteria-&gt;condition = &quot; 1=1 &quot;;
$criteria-&gt;with         = array(&#39;teacher&#39;=&gt;
array(&#39;select&#39;=&gt;&#39;username,company_id&#39;,
 &#39;order&#39;=&gt;&#39;teacher.username ASC&#39;)
);
</pre>
<p>
	这样才能减少载入的字段。</p>
<p>
	试想，如果通过方法实例化本类的时候通过defaultScope()方法获取字段，with相关类的时候只取我们需要的字段就好多了，Yii可以！</p>
]]></description>
<link>http://www.chenggang.net/posts/112</link>
<pubDate>Wed, 21 Dec 2011 18:13:09 +0800</pubDate>
<author>admin</author>
<category>Web进阶</category>
<guid isPermaLink="true">http://www.chenggang.nethttp://www.chenggang.net/posts/112</guid>
</item>
</channel></rss>
