P
P
pavel singree2015-06-30 14:51:46
Yii
pavel singree, 2015-06-30 14:51:46

How to write a complex SQL query using COUNT in Yii2?

Help compose a complex query using ActiveRecord

SELECT *
                    FROM  trips
                    LEFT JOIN  attachments ON (  attachments.parent_id =  trips.id )
                    LEFT JOIN  points ON (  points.parent_id =  trips.id )
                    WHERE (
                        SELECT COUNT( * ) AS count1
                        FROM  yattachments
                        WHERE  attachments.doc_id =1
                        AND attachments.parent_id =  trips.id
                    ) = (
                        SELECT COUNT( * ) AS count2
                        FROM  points
                        WHERE  points.parent_id =  trips.id 
                        ) + 2
                    AND (
                        SELECT COUNT( * ) AS count3
                        FROM  attachments
                        WHERE  attachments.doc_id =2
                        AND  attachments.parent_id =  trips.id
                    ) = (
                        SELECT COUNT( * ) AS count2
                        FROM  points
                        WHERE  points.parent_id =  trips.id 
                    ) + 2

The model has both relationships
public function getPoints()
    {
        return $this->hasMany(Points::className(), ['parent_id' => 'id']);
    }

    public function getAttachments()
    {
        return $this->hasMany(Attachments::className(), ['parent_id' => 'id']);
    }

I don't know how to put conditions in the where method
$query = Trips::find()
                ->joinWith('attachments')
                ->joinWith('points')
                ->where(['doc_id' => [1,2]])
            ;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question