Yii2中如何使用日期格式获取月份和年份

How to use date format to get month and year in Yii2

假设我有一个 table

Date    Item    Qty
15/1/2016   Item1   10
16/1/2016   Item1   20
16/2/2016   Item1   30
18/2/2016   Item1   10

并且在报告中我想这样显示

Month   Qty
01-2016 30
02-2016 40

请告诉我如何在 Yii2 中执行此操作。

我已经在我的 SearchModel 中尝试了以下方法。

$query = Productsalesdetails::find()
        ->select(['DATE_FORMAT(date, "%m-%Y"),productname,sum(total) as total'])
        ->groupBy('DATE_FORMAT(date, "%m-%Y")');

查询也使用字母 select 和 date_format 的别名..

$query = Productsalesdetails::find()
    ->select( 'DATE_FORMAT(date, "%m-%Y") as m_date, productname, sum(total) as total')
    ->groupBy ('m_date, productname');

事实上你已经有了select中的格式你可以在属性中使用别名

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'summaryOptions' => ['class' =>'dfenx_pagination_summary',],
    'pager' => ['options' => ['class'=> 'pagination pull-right']],
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        [
           'attribute' => '', 
           'label' => 'Month',  
           'value' => function ($model) {       
                return $model->m_date;
           },        
        ],
        [
           'attribute' => 'productname', 
           'label' => 'Item',  
        ],
         [
           'attribute' => '', 
           'label' => 'Total',  
           'value' => function ($model) {       
                return $model->total;
           },        
        ],

       ....

    ]); 

这应该可以在不在模型中为别名添加 $var 的情况下工作.. 否则你需要你的模型

class YourModel extends \yii\db\ActiveRecord
{
   public $m_date;
   public $total;
   .....