2012-03-27 7 views
-1

私のブログに「アーカイブ」を作成してください。使用不可能な項目の検索が実行された場合、戻り値は空の​​オブジェクトです。ここに私のコードです:Kohana 3.2 - データベース検索で空のオブジェクトが返される

たとえば、間違った入力の場合:

http://www.my-site.com/archive/2011/01/27 - データベースにこの日付の無柱2011-01-27

コントローラのアクション:

public function action_archive() { 
    $posts_model = new Model_Posts(); 

    // Év pl.: 2012 
    if($year = $this->request->param("year")) { 
     // Hónap pl.: 2012-03 
     if($month = $this->request->param("month")) { 
      // Nap pl.: 2012-03-27 
      if($day = $this->request->param("day")) { 
       if ($posts = $posts_model->get_post_by_date($year . "-" . $month . "-" . $day)) { 
        $this->template->content = View::factory('posts/default') 
         ->bind('posts', $posts); 
       } else 
        throw new HTTP_Exception_404; 
      } else { 
       if($posts = $posts_model->get_post_by_date($year . "-" . $month)) { 
        $this->template->content = View::factory('posts/default') 
         ->bind('posts', $posts); 
       } else 
        throw new HTTP_Exception_404; 
      } 

     } else { 
      if($posts = $posts_model->get_post_by_date($year)) { 
       $this->template->content = View::factory('posts/default') 
        ->bind('posts', $posts); 
      } else 
       throw new HTTP_Exception_404; 
     } 
    } else 
     // Nem található archívum 
     throw new HTTP_Exception_404; 

    return false; 
} 

I検索が失敗した場合、404例外をスローしようとしています。こちらのモデルは来る:

public function get_post_by_date($date) { 
    try { 
     return DB::select() 
      ->from("posts") 
      ->where("date", "like", "$date%") 
      ->and_where("publish", "=", "1") 
      ->as_object() 
      ->execute(); 
    } catch (Database_Exception $e) { 
     Kohana::$log->add(Log::ERROR, Database_Exception::text($e)); 
    } 

    return false; 
} 
+0

問題が何ですか。質問を編集して指定してください – illEatYourPuppies

+0

プロファイラをオンにして、SQLが実行されていることを確認してください。 – zombor

+0

投稿が実際に質問を含んでいれば、それはより良いでしょう... –

答えて

0

データベースの使用 内の特定のエントリがあるかだけをチェックする必要がある場合 - >()を実行 - >数()は、

実際の投稿が必要なので、Database_Resultクラスのcountメソッド(Countableインターフェイスを実装しています)を使用することができます。

$posts = $posts_model->get_post_by_date($year . "-" . $month . "-" . $day); 
if ($posts->count()) { 
    $this->template->content = View::factory('posts/default') 
     ->bind('posts', $posts); 
} else 
    throw new HTTP_Exception_404; 

try-catchブロックを削除します。あなたの質問が正しいなら、あなたはそれを必要としません。

関連する問題