4

In Craft 2 you could creat a query with:

craft()->db->createCommand()->select() .... etc.

But in Craft 3 there is no select() Method in Craft::$app->db->createCommand().

Am I overlooking something?

9

You can use either an activeRecord for it

$customer = Customer::find() 
    ->where(['id' => 123]) 
    ->one();

Or a query

$rows = (new \craft\db\Query()) 
    ->select(['id', 'email']) 
    ->from('user') 
    ->where(['last_name' => 'Smith']) 
    ->limit(10)
     ->all();
| improve this answer | |
  • Forgive my ignorance, but how would you then return the $rows array to your twig template? – Jim Pannell Aug 27 '18 at 19:55
  • 1
    @JimPannell It depends on what you are doing. If you call this function via Variable you can just return it. If you call it via controller request you can render it return $this->renderTemplate('path/to/template' ['data' => $rows]) if it is an ajax request you need to encode it to json within your Controller return $this->asJson(['data' => $rows]); It's hard to tell without further information – Robin Schambach Aug 27 '18 at 20:09
  • Thanks @Robin-Schambach. It's actually in a service file (I understood this is where most of my DB calls should be in Craft 3). – Jim Pannell Aug 27 '18 at 20:27
  • Services always only return it variables and controllers proceed those values and pass them to Twig/JS/whatever – Robin Schambach Aug 27 '18 at 20:29
  • 1
    I'm new to Craft dev work and have been finding the lack of Craft 3 examples and documentation really hard going. Your comments help a lot - thanks. – Jim Pannell Aug 27 '18 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.