命名空間其實就是設置查詢條件,當然也可以用作update,delete的條件了。
要使用命名空間,就在AR類中覆蓋方法 scopes 。
廢話少說,示例如下:
在Tag類中覆蓋scopes :
//命名範圍測試 , 命名範圍這個函數scopes 應該定義在AR類裏面
public function scopes(){
return array(
'newTag'=>array(
'condition'=>'name=:name',
'params'=>array(
':name'=>'newTag',
),
),
'recently'=>array(
'order'=>'id DESC',
'limit'=>4,
),
);
}
然後在一個控制器中測試一下: 這樣就能查詢到scopes中過濾得到的數據了。
public function actionScopes(){
//命名範圍 scopes 測試
$tags = Tag::model()->newTag()->recently()->findAll();
foreach($tags as $tag){
echo $tag->id." ";
echo $tag->name." ";
echo $tag->frequency."<br>";
}
}
Comment中的scopes方法 :
//命名空間,設置查詢條件
public function scopes(){
return array(
'approved'=>array(
'condition'=>'t.status='.self::STATUS_APPROVED,
),
'recently'=>array(
'order'=>'t.create_time DESC', // 這裏最好指明是主表吧,否則可能會出錯
'limit'=>5,
),
);
}
Post類中的scopse方法:
//命名空間的使用。其實就是設置查詢條件
public function scopes(){
return array(
'published'=>array(
'condition'=>'status='.self::STATUS_PUBLISHED,
),
'recently'=>array(
'order'=>'update_time DESC',
'limit'=>3,
),
);
}
控制器測試方法:
public function actionScopes(){
echo "<hr>關聯查詢和命名空間搭配使用<br>";
$posts = Post::model()->recently()->published()->with('comments')->findAll();
foreach($posts as $post){
echo $post->id." |";
foreach($post->comments as $comment){
echo $comment->id.": ";
echo $comment->content."<br>";
}
echo $post->author->username."<br>";
}
echo "<hr>關聯查詢和命名空間搭配使用<br>";
$posts = Post::model()->with("comments:recently:approved")->findAll();
foreach($posts as $post){
echo $post->id." |";
foreach($post->comments as $comment){
echo $comment->id.": ";
echo $comment->content."<br>";
}
echo $post->author->username."<br>";
}
echo "<hr>";
}
命名空間可以和關聯查詢聯合使用,上面就是這樣的例子。