Answer the question
In order to leave comments, you need to log in
Form an AR query with YII2 conditions?
$query = (new \yii\db\Query());
$query->select('*');
$query->from('docs');
if($status_id==1 || $status_id==null)
{
$query->where(['>=','status_id',-1]);
}
else{
$query->where(['=','status_id',$status_id]);
}
if($from1!=null)
{
$query->andWhere(['>=','bterm',$from1]);
}
if($to1!=null)
{
$query->andWhere(['<=','eterm',$to1]);
}
$data=$query->all();
Answer the question
In order to leave comments, you need to log in
so in juii2 the activerecord is inherited from the builder
$docs = Docs::find();
if($status_id==1 || $status_id==null) {
$docs->where(['>=','status_id',-1]);
}else {
$docs->where(['status_id'=>$status_id]);
}
$data=$docs->andFilterWhere(['>=','bterm',$from1])
->andFilterWhere(['<=','eterm',$to1])
->all();
$query = Docs::find();
And then like you. :) I hope you already have a Dosc model that inherits from ActiveRecord. Not? Then you can generate it via Gii.
upd: If the question is how "Beautifully write down the conditions"? That in your case - your variant is simpler and more readable.
upd2: Oh yes. There andFilterWhere can be used as pointed out by sidni
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question