Dynamic yii\db\ActiveRecord::find()

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();

Thank you, that worked!

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

Nice concise way to do it. I assume this will work with the andWhere as well?

What do you mean?

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();

Yes it will.
But careful because the behaviors are different when condition evaluates to false and so null is passed:

  1. With filterWhere, this whole condition is ignored and query becomes
    SELECT col1, col2, col3 FROM stables WHERE stopic_id = whatever_id_is LIMIT 1
  2. 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

Thanks for the explanation. Learned something today.

1 Like