如何写yii2中的查询之间的位置

时间:2016-09-04 15:17:29

标签: php mysql yii2

我传递$start_date$end_date作为参数,将它们与MySQL数据库表中的created字段进行比较。我正在使用yii2框架。

以下是我的尝试:

$modelStockDetails=StockDetails::find()->where(['BETWEEN', 'created', $start_date, $end_date])->andwhere(['receiving_order_id' =>$modelRecevingOrder->id,'deleted' => 'N'])->all();
当值$start_date$end_date与表中的created日期不同时,

会返回一个空数组。

但是当我传递$start_date时,它会返回一个包含数据的数组,这与表中的created日期完全相同。

1 个答案:

答案 0 :(得分:1)

可能是与输入转换相关的问题尝试使用str_to_date和文字Where (根据您的格式使用正确的日期格式转换,我的样本是“%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();

或者为了避免在sql中使用var,你可以使用

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