本文實(shí)例講述了Yii中的relations數(shù)據(jù)關(guān)聯(lián)查詢(xún)及統(tǒng)計(jì)功能用法。分享給大家供大家參考,具體如下:
關(guān)聯(lián)查詢(xún),Yii 也支持所謂的統(tǒng)計(jì)查詢(xún)(或聚合查詢(xún))。 它指的是檢索關(guān)聯(lián)對(duì)象的聚合信息,例如每個(gè) post 的評(píng)論的數(shù)量,每個(gè)產(chǎn)品的平均等級(jí)等。 統(tǒng)計(jì)查詢(xún)只被 HAS_MANY(例如,一個(gè) post 有很多評(píng)論) 或 MANY_MANY (例如,一個(gè) post 屬于很多分類(lèi)和一個(gè) category 有很多 post) 關(guān)聯(lián)對(duì)象執(zhí)行。
執(zhí)行統(tǒng)計(jì)查詢(xún)非常類(lèi)似于之前描述的關(guān)聯(lián)查詢(xún)。我們首先需要在 CActiveRecord 的 relations() 方法中聲明統(tǒng)計(jì)查詢(xún)。
class Post extends CActiveRecord
{
public function relations()
{
return array(
'commentCount'=>array(self::STAT, 'Comment', 'post_id'),
'categoryCount'=>array(self::STAT, 'Category', 'post_category(post_id,category_id)'),
);
}
}
關(guān)聯(lián)查詢(xún)命名空間
關(guān)聯(lián)查詢(xún)也可以和 命名空間一起執(zhí)行。有兩種形式。第一種形式,命名空間被應(yīng)用到主模型。第二種形式,命名空間被應(yīng)用到關(guān)聯(lián)模型。
下面的代碼展示了如何應(yīng)用命名空間到主模型。
代碼如下:
$posts=Post::model()->published()->recently()->with('comments')->findAll();
這非常類(lèi)似于非關(guān)聯(lián)的查詢(xún)。唯一的不同是我們?cè)诿臻g后使用了 with() 調(diào)用。 此查詢(xún)應(yīng)當(dāng)返回最近發(fā)布的 post和它們的評(píng)論。
下面的代碼展示了如何應(yīng)用命名空間到關(guān)聯(lián)模型。
代碼如下:
$posts=Post::model()->with('comments:recently:approved')->findAll();
上面的查詢(xún)將返回所有的 post 及它們審核后的評(píng)論。注意 comments 指的是關(guān)聯(lián)名字,而 recently 和 approved 指的是 在 Comment 模型類(lèi)中聲明的命名空間。關(guān)聯(lián)名字和命名空間應(yīng)當(dāng)由冒號(hào)分隔。
命名空間也可以在 CActiveRecord::relations() 中聲明的關(guān)聯(lián)規(guī)則的 with 選項(xiàng)中指定。在下面的例子中, 若我們?cè)L問(wèn) $user->posts,它將返回此post 的所有審核后的評(píng)論。
class User extends CActiveRecord
{
public function relations()
{
return array(
'posts'=>array(self::HAS_MANY, 'Post', 'author_id', 'with'=>'comments:approved'),
);
}
}
希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。
版權(quán)所有:易賢網(wǎng)