0

I have a problem concerning CakePHP SQL-queries. I need to fetch products from the database where shop_id is given and then count the products. All I need is Product.url and its count.

This will do the trick in plain SQL:

SELECT url,COUNT(*) as count FROM products GROUP BY url ORDER BY count DESC;

This one I used to get all products relating to shops:

$this->Product->find('all', array('conditions' => array('Product.shop_id'=>$id)));

That works correctly, but I need to convert that SQL-query above to CakePHP.

I tried something like this:

$this->Product->find('count', array('conditions' => array('Product.shop_id'=>$id),
                                        'fields'=>array('Product.url','Product.id'),
                                        'order'=>'count DESC',
                                        'group'=>'Product.url'));

That returns only an int. But if I run that SLQ-query presented above in mysql server, I get two columns: url and count. How do I get the same results with CakePHP?

1

3 Answers 3

2

You can try this:

$data = $this->Post->query(
    "SELECT COUNT(id),MONTH(created) FROM posts GROUP BY YEAR(created), MONTH(created);"
);
Sign up to request clarification or add additional context in comments.

Comments

1

The most easiest way to do this:

$this->Product->query("SELECT url,COUNT(*) as count FROM products GROUP BY url ORDER BY count DESC;");

...at least for me.

Comments

1

Try the following code:

$this->Product->virtualFields['CNT_PRODUCTS'] = 0;
$this->Product->find('count', array('conditions' => array('Product.shop_id' => $id),
                                    'fields' => array('Product.id', 'Product.url', 'count(*) as CNT_PRODUCTS'),
                                    'order' => array('CNT_PRODUCTS' => 'DESC'),
                                    'group' => 'Product.url'));

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.