How to write where Between query in yii2

冷暖自知 提交于 2019-12-24 09:26:17

问题


I am passing $start_date and $end_date as parameter to compare them with created field in MySQL database table. I am using yii2 framework.

Here is what I tried:

$modelStockDetails=StockDetails::find()->where(['BETWEEN', 'created', $start_date, $end_date])->andwhere(['receiving_order_id' =>$modelRecevingOrder->id,'deleted' => 'N'])->all();

which returns an empty array when values $start_date and $end_date are different from created date in the table.

But it returns an array containing the data when I pass $start_date which is exactly same as created date in the table.


回答1:


Could be a problem related to the conversion of the input try using a str_to_date and literal Where (use a proper date format conversion based on your format im my sample is "%d-%m-%Y")

$modelStockDetails=StockDetails::find()
  ->where(' date(created) between STR_TO_DATE("'.  $start_date . '", "%d-%m-%Y" ) 
        AND   STR_TO_DATE("' .  $end_date . '", "%d-%m-%Y" )' )
  ->andwhere(['receiving_order_id' =>$modelRecevingOrder->id,'deleted' => 'N'])->all();

or for avoid the use of var in sql you could use

$modelStockDetails=StockDetails::find()
->where(' date(created) between STR_TO_DATE(:start_date, "%d-%m-%Y" ) 
      AND   STR_TO_DATE( :end_date, "%d-%m-%Y" )', [':start_date' => $start_date, ':end_date' => $end_date] )
->andwhere(['receiving_order_id' =>$modelRecevingOrder->id,'deleted' => 'N'])->all();


来源:https://stackoverflow.com/questions/39318434/how-to-write-where-between-query-in-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!