0

controller/indexCakePHP2アプリのアクションで、

$this->Model-find('all',array( ... lots conditions and things... ));

次に、controller/view私は持っています:

$this->Model-find('first',array( ... lots conditions and things... ));

これらは両方とも非常にうまく機能しますが、私は明らかに大量のコード(つまり、検索条件、フィールドリストなど)を繰り返していますが、最初のコードとfind('all')2番目のコードの違いは2つだけです。find('first')条件の1つとしてIDを実行して提供しています。

条件をモデルに移動してから、それらの条件でさまざまなタイプの検索を実行する方法はありますか?

4

3 に答える 3

0

はい、クエリを関数/メソッドとしてモデルクラスに移動できます。ポストモデルについては、以下のサンプルを参照してください。

class Post extends AppModel {
    public $name = 'Post';

    public function getAll() {
       return $this->find('all', array('limit' => 20, 'order' => 'Post.created DESC'));
    }
}

そして、コントローラーで$ this-> Model-> getAll();によって呼び出します。

$this->Post->getAll();

関数にパラメーターを追加することもできます。

于 2012-09-24T04:05:04.793 に答える
0

Youurモデルでメソッドを作成できます。

public function getConditions($id = null) {
   return array( ... lots conditions and things... );
}

このメソッドのどこかで、(!empty($id))正しい結果を返すかどうかをテストするだけです。(あなたは「条件と物事」を提供していないので、ここに正確なコードを書くことはできません...

両方のコントローラーアクションで使用します。

$this->Model->find('first', $this->Model->getConditions()));

$this->Model->find('all', $this->Model->getConditions()));
于 2012-09-24T08:20:17.477 に答える
0

コントローラの属性として条件を追加します

class FoosController extends AppController{

    public $conditions = array( ... lots conditions and things... )

    public function index(){
        $this-Foo->find('all', $this->conditions);
    }

    public function view(){
        $this-Foo->find('first', $this->conditions);
    }
}
于 2012-09-24T08:37:59.043 に答える