We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Criteria vs QueryBuilder

Hello,

I'm trying to make universal grid. I'm setting data to grid by giving the criteria instance, examples:

        $criteria = Bendrijos::query();
        if (!$this->user->admin)
            $criteria->innerJoin('Usertobendr', 'ub.bendr_id = Bendrijos.id', 'ub')
                ->andWhere('ub.user_id = :id:')
                ->bind(array('id' => $this->user->id));

        $grid->setData($criteria);
        $criteria = Users::query();

        $grid->setData($criteria);

It is working at this moment, but I came to pagination task. I didn't checked before, so I have problem, because Phalcon\Paginator accepts only QueryBuilder instance.

  1. Is it possible somehow to workaround paginator to accept criteria as param?
  2. Actually querybuilder methods are similar to criteria, so I can use querybuilder instead of criteria, but how to get similar instance?:
Users::query() == $this->modelsManager->createBuilder()->from('Users')

?



3.2k
Accepted
answer
Users::query() == $this->modelsManager->createBuilder()->from('Users')

Not === but similar:

$builder = $this->modelsManager->createBuilder()->from('Bendrijos')
if (!$this->user->admin)
{
    //You need to bind right when you do where/andWhere/etc
    $builder->innerJoin('Usertobendr', 'ub.bendr_id = Bendrijos.id', 'ub')
        ->andWhere('ub.user_id = :id:', array('id' => $this->user->id))
}

Plus you get the ability to groupBy() and use having() (I guess only for mysql)

One more thing. Why do we need the criteria at all? Why Model::query() cannot return query/builder instance?

I don't know, I've questioned myself some times ago: http://forum.phalcon.io/discussion/1479/multiple-joins-in-oo-notation-fail#C5783

It's not because Model::find() uses it because they use Builder: https://github.com/phalcon/cphalcon/blob/bf9da26e6e20ea05dd69881b9cd0c2536ec53bcb/ext/mvc/model.c#L1369

Still, it should be easier once Phalcon reach 2.0 to refactor Criteria out and use builder only

edited Aug '14

what I'm still wondering is how the reputation works, i was at 1K before, and now i'm at 882?

EDIT: wait 877

edited Aug '14

I already read that page. I'm back to 882 now... how can i get -130 in a day without deleting a post?

EDIT: back to 877 from 892... seems completely random to me :)