D
D
Dauren S2018-08-08 16:17:24
Yii
Dauren S, 2018-08-08 16:17:24

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

How to do the same with AR only?
I mean that it is necessary to make a request depending on the conditions.
Depending on if there is a period, it must be added to where, if not, then do not add it. And depending on the transferred data to make a request.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis, 2018-08-08
@dauren101

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

L
Lander, 2018-08-08
@usdglander

$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 question

Ask a Question

731 491 924 answers to any question