snathan
(snathan)
1
Need help constructing a variable/dynamic yii\db\ActiveRecord::find() method. Below is what I have:
$modelS = Stable::find()->select(['col1', 'col2', 'col3'])
->andWhere('stopic_id = :vtpid')
//->andWhere(['created_by' => 1])
->params([':vtpid' => $varid])
->one();
if ($something == $anotherthing)
include this: andWhere(['created_by' => 1]) to the above condition.
Thanks
$modelS = Stable::find()->select(['col1', 'col2', 'col3'])
->andWhere('stopic_id = :vtpid')
->params([':vtpid' => $varid]);
if ($something == $anotherthing){
$modelS->andWhere(['created_by' => 1]);
}
$modelS = $modelS->one();
evstevemd
(Stefano Mtangoo)
4
Another shorter but “less readable”
$modelS = Stable::find()->select(['col1', 'col2', 'col3'])
->andWhere(['stopic_id => $varid])
->andFilterWhere(['created_by' => $something == $anotherthing ? 1 : null])
->one();
Also your query can be written without params thing!
1 Like
snathan
(snathan)
5
Nice concise way to do it. I assume this will work with the andWhere
as well?
snathan
(snathan)
7
I mean will this work too?
$modelS = Stable::find()->select(['col1', 'col2', 'col3'])
->andWhere(['stopic_id => $varid])
->andWhere(['created_by' => $something == $anotherthing ? 1 : null])
->one();
evstevemd
(Stefano Mtangoo)
8
Yes it will.
But careful because the behaviors are different when condition evaluates to false and so null is passed:
- With filterWhere, this whole condition is ignored and query becomes
SELECT col1, col2, col3 FROM stables WHERE stopic_id = whatever_id_is LIMIT 1
- with where create_by is compared against null
SELECT col1, col2, col3 FROM stables WHERE stopic_id = whatever_id_is AND created_by IS NULL LIMIT 1
There is no difference in query when the condition evaluates to true!
1 Like
snathan
(snathan)
9
Thanks for the explanation. Learned something today.
1 Like