Kohana 3.2 - Поиск в базе данных возвращает пустой объект - PullRequest
0 голосов
/ 27 марта 2012

Попробуйте сделать «архив» для моего блога. Если поиск выполняется для недоступных элементов, возвращаемое значение - пустой объект. Вот мой код:

Например, неверный ввод:

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;
}

Я пытаюсь выдать исключение 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;
}

1 Ответ

0 голосов
/ 03 апреля 2012

Если вам нужно просто проверить, есть ли конкретная запись в базе данных, используйте -> execute () -> count ();

В вашем случае вам понадобятся реальные сообщения, поэтому вы можете использоватьметод count класса Database_Result (он реализует интерфейс 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.Вам это не нужно, если ваш запрос правильный.

...