Phalcon: find() + Paginator

3.2k views Asked by At

I have a MySQL database and a table within it. The mission is to set a method, which will receive 2 parameters(?user_id=...&action_id...) and search for records matching these two fields or one of them, if only one was set(?user_id=...), then paginate them and send them to the action view. I've just started to learn Phalcon a week ago, have done some research here and there, read the docs and still don't realize how i can do this. What i've done so far:

public function searchAction()
{

    $userID = $this->request->get("user_id", "int", 0);
    $actionID = $this->request->get("action_id", "int", 0);

    $currentPage = 1;
    $currentPage = (int) $_GET["page"];
    $parameters = array(
                'user_id' => $userID,
                'action_id' => $actionID
            );

            $o = History::find($parameters);

            $paginator = new Paginator(array(
                "data" => $o,
                "limit" => 10,
                "page" => $currentPage
            ));
            $page = $paginator->getPaginate();

            $this->view->setVar("page", $page);

}

Pagination is working somehow but the search is not, why?

2

There are 2 answers

0
Jeckerson On BEST ANSWER

First parameter in the method find() or findFirst() must be a string to set conditions to the query.

In your case, you can search like that:

$o = History::find('user_id = "'.$userID.'" AND action_id = "'.$action_id.'"');

But, if you want add more parameters, then you need to pass array and the first element must contain search conditions:

$o = History::find(array(
   'user_id = "'.$userID.'" AND action_id = "'.$action_id.'"',
   'limit' => 10,
   'order' => 'user_id ASC'
));
0
jumper85 On

Referring to official documentation http://docs.phalconphp.com/en/latest/reference/models.html#binding-parameters

$conditions = "user_id = ?1 AND action_id = ?2";
$parameters = array(1 => userID, 2 => $actionID);
$o = History::find(array(
    $conditions,
    "bind" => $parameters
));

Index of parameters array must match number of placeholder in conditions string.