As for complexity SQL query we have two solutions as below, I will discuss #2 in this article.
This is how i do before query on Yii 2.0