E
E
Evgeny Bukharev2015-12-19 22:42:01
Yii
Evgeny Bukharev, 2015-12-19 22:42:01

How to properly compose a DbDependency in Yii2?

There is the following code, a selection from the database of the most visited articles:

if (!$data = Yii::$app->cache->get('recent_list_post')) {
            $data = Post::find()
                ->with(['imageR', 'categoryR'])
                ->active()
                ->orderBy('hits DESC')
                ->limit(4)
                ->all();

            $dependency = new DbDependency([
                'sql' => 'SELECT SUM(hits) FROM ' . Post::tableName() . 'WHERE status=' . Post::STATUS_ACTIVE . ' ORDER BY hits DESC limit 4',
            ]);
            Yii::$app->cache->set('recent_list_post', $data, 60*60, $dependency);
        }
        $this->data = $data;

How to correctly compose a DbDependency to track whether the composition of the 4 most visited articles has changed?
It would seem that SUM(hits) or SUM(id) or SUM(hits*id) would be logical, but SUM does not perceive LIMIT but calculates the sum of all records in the table.
How to rewrite the query so that DbDependency sql get something like a hash from the id or hits of the last 4 articles?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Bukharev, 2015-12-20
@evgenybuckharev

Here's the solution if anyone needs it:

SELECT SUM(s.id)*SUM(s.hits) FROM (SELECT p.hits,p.id FROM `htc_post`as p WHERE p.status=2 ORDER BY p.hits DESC LIMIT 4) as s

S
Sergey, 2015-12-20
@sfedosimov

Not the best option, but the first thing that came to mind can be done with a nested query, where first pull out the top 4, and then make a sum on them

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question