Quinlanlent Quinlanlent - 1 year ago 70
MySQL Question

Build the 'AND' query in yii 2

Hello I am trying to find out what method/way is used so that I can build an 'AND' query in my code because I suspect that the query I have been using right now uses the 'OR' query see the code below.

I think this is the building the 'OR' query:

ActiveSubject::find()->where(['clientid' => $clientid,
'subjectid' => $subjects['subjectid'],]);

I have searched around the internet and people have suggested using

ActiveSubject::find()->select(['clientid', 'subjectid'])
->andWhere(['clientid' => $_user,])
->andWhere(['subjectid' => $subjects['subjectid'],]);

But still suspect it is still using 'OR' because the output is still getting everything rows with clientid even though there is no related subjectid. Can you help me finding out what the proper method of building a 'WHERE' query in yii 2?


I was doing this:

<?php if(ActiveSubject::find()->where(['clientid' => $_user,
'subjectid' => $subjects['subjectid'],]))://if true? ?>

<!--do this-->

<?php else: ?>

<!--do this-->

<?php endif; ?>

But alas it is not doing the
when the query fails.


My goal was the if function on my end, but I thought the reason it was not working was because of the query that it was not fulfilling the boolean but then it is actually returning an instance of ActiveQuery and I realized I was wrong. So it would make more sense if I make a function that returns a boolean in the ActiveSubject Model.

Answer Source

The first one uses AND and it's the same as the second one. If you are not sure about produced SQL check your debugger output or call something like:

echo ActiveSubject::find()
        'clientid'  => $clientid,
        'subjectid' => $subjects['subjectid']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download