投稿記事作成時間をDESC順(降順)にする方法
posts_contoroller.phpのなかにあるfunction index()
公式チュートリアルの/posts/indexの部分が
function index() { $this->set('posts', $this->Post->find('all')); }
で、
find()はデータを取得するメソッド。
find($type, $params)
$typeは取得方法を指定する。上記は'all'なので全てのデータを取得することになっている。このままでおk。
$paramsはパラメータ指定。配列で書く必要がある。array()で。パラメータはSQL文のWHEREやGROUP BYとかのようなもの。
色々ググって見ると、1.1や1.2の違いとか情報が氾濫してます><
ちなみに公式マニュアルにはfindAll()は非推奨で、find('all')と書きなさいということ。
公式マニュアル内を調べてみると、
http://book.cakephp.org/ja/view/449/find
パラメータ部分の参考コードがあったので試す。
パラメータ
array( 'conditions' => array('Model.field' => $thisValue), //array of conditions 'recursive' => 1, //int 'fields' => array('Model.field1', 'Model.field2'), //array of field names 'order' => array('Model.created', 'Model.field3 DESC'), //string or array defining order 'group' => array('Model.field'), //fields to GROUP BY 'limit' => n, //int 'page' => n, //int 'callbacks' => true //other possible values are false, 'before', 'after' )
改良したもの(function index()のみ抜粋)
function index() { $params = array( 'limit' => 10, 'order' => array('created DESC') ); $this->set('posts', $this->Post->find('all',$params)); }
テーブル内の作成時間のカラム名が'created'なのでそこにDESCとして呼び出す。
ついでに取得データの制限としてlimit指定が可能なので'limit' => 10 と書くようだ。
調教したコード(このやろう!だから(ry
<?php class PostsController extends AppController { var $name = 'Posts'; // var $components = array('Auth'); // Not necessary if declared in your app controller function index() { $params = array( 'limit' => 10, 'order' => array('created DESC') ); $this->set('posts', $this->Post->find('all',$params)); //find('all')); } function view($id) { $this->Post->id = $id; $this->set('post', $this->Post->read()); } function add() { if (!empty($this->data)) { if ($this->Post->save($this->data)) { $this->flash('Your post has been saved.','/posts'); } } } function delete($id) { $this->Post->del($id); $this->flash('The post with id: '.$id.' has been deleted.', '/posts'); } function edit($id = null) { $this->Post->id = $id; if (empty($this->data)) { $this->data = $this->Post->read(); } else { if ($this->Post->save($this->data['Post'])) { $this->flash('Your post has been updated.','/posts'); } } } function login() { } function logout() { $this->redirect($this->Auth->logout()); } function beforeFilter() { // $this->Auth->allow('index','view'); $this->Auth->allow('index'); } } ?>