问题
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