2011年06月17日

cakephp paginate を modelに書いて option で分ける

 
fields の値が count の時にあるとバグるので、
countの時に fields を unset するだけでいいかも。

モデル
function find($type, $q = array())
{
    
if(isset($q['option'])){
    switch($q['option']){
        
        case 'fortune':
            $default = array( 
                'limit' => 20,  
                'order' => array('Teller.id' => 'desc'),
                'conditions' => array('Teller.hasphoto' => '1'),
                'fields' => array('id','name','fortunes','coupon','vip','show','uranairekiday'),
            );
            
            $q = Set::merge($q,$default);
            
            if($type == 'count'){
                unset($q['fields']);
            }
        
        case 'show':
            $default = array( 
                'limit' => 20,  
                'order' => array('Teller.id' => 'desc'),
                'conditions' => array('Teller.hasphoto' => '1'),
                'fields' => array('id','name','fortunes','coupon','vip','show','uranairekiday'),
            );
            
            $q = Set::merge($q,$default);
            
            if($type == 'count'){
                unset($q['fields']);
            }
            
            
        break;
        
    }
    
}




・コントローラー
function show()
{

    $this->paginate = array(
        'Contact' =>
        array(
            'option' => 'free_now'
        )
    );
                
    $res = $this->paginate('Contact');
    
    $this->set(
        compact(
            'res'
        )
    );
}



・モデル

<?
class Contact extends AppModel {

function find($type, $q = array())
{

if(isset($q['option'])){
switch($q['option']){

case 'free_now':

$opq = array(
'conditions' => array(
'teller_id' => 0,//無料占いのみ
'subcontact_count <' => 3
),
'fields' => array('Contact.id','Contact.user_id','Contact.message','Contact.subcontact_count'),
'order' => array('Contact.id' => 'desc'),
'limit' => 20,
'recursive' => 3
);

if($type != 'count'){

$this->Subcontact = Classregistry::init('Subcontact');
$this->Subcontact->bindModel(array('belongsTo' => array('Teller' => array('foreignKey' => 'from_id'))) , false);

$this->bindModel(array('belongsTo' => array('User')) , false);
$this->bindModel(array('hasMany' => array('Subcontact')) , false);

$q = Set::merge($q,$opq);
} else {
$q = Set::merge($opq['conditions'],$q['conditions']);
}



break;

}
}

return parent::find($type, $q);
}


}

?>


でいける。
ここでのコツは、paginate は

・count メソッドで一回
・all メソッドで一回

findを読み出す。

count するときに conditions 以外のものが含まれているとエラーになるので、
count で動くときはconditions 以外はセットしないようにする。
関連するタグ: Dreamweaver cakephp
あなたにとって有用な記事でしたか?是非ブックマークしておくことをおすすめします。
 




ライブラリを配布しちゃったり
webデザイン
HTMLコーディング
CSS
Fireworks
Dreamweaver
携帯サイト
webプログラム
PHP
正規表現
cakephp
MYSQL
javascript
webマーケティング
adwords
analytics
windows7
ショートカットキー
おすすめ情報
サイト
facebook
ライブラリ
配布
アプリ
iphone
ipad
サーバー
さくらサーバー
全ての記事を読む


[ うらこ先生を応援する! ]
by相性占い.net



トップ - 最新の記事一覧 - お問い合わせ