从MySQL查询结果-Doctrine2创建关联数组



我正在从事Symfony2项目,我需要使用一个插件来进行日历,该日历需要以下值:

JS

 $.ajax({
   type: 'POST',
   url: Routing.generate('example'),
   data: {},
   dataType: 'json',
   success: function(response) {
    $('#calendar').eCalendar({
    ...
    events: [{
       title: 'Example Title 1', 
       description: 'Description 1.', 
       datetime: new Date(2016, 11, 30) 
    },
    {
       title: 'Example Title 2', 
       description: 'Description 2.', 
       datetime: new Date(2016, 10, 23), 
    }]
  });
 }
})

这些事件数据可以如下通过AJAX传递:

JS

 $.ajax({
   type: 'POST',
   url: Routing.generate('example'),
   data: {},
   dataType: 'json',
   success: function(response) {
    for (var i = 0; i < response.data.length; i = i + 1) {
      str=response.data[i].datetime.date;
      year=str.substring(0,4);
      month=str.substring(5,7);
      day=str.substring(8,10);
      var myDate = new Date(year,month-1,day);
      response.data[i].datetime = myDate;
    }
    $('#calendar').eCalendar({
    ...
    events: response.data
  });
 }
})

php

public function exampleAction()
{
 $arr = array(array("title" => 'Example Title 1',"description" => "Description 1.","datetime"=>new DateTime("now")),
        array("title" => 'Example Title 2',"description" => "Description 1.","datetime"=>new DateTime("now"))
    );
    return new JsonResponse(array(
        'data' =>$arr,
        'success' => true), 200);
}

到目前为止一切都很好。但是现在我需要从数据库中的下表获取这些数据:

id  title               description     datetime                   category     hour    
1   Example Title 1     Description 1.  2016-12-21 00:00:00     general     all day     
2   Example Title 2     Description 2.  2016-12-21 00:00:00     general     09:00 

在我的存储库类中,我使用以下代码查询:

public function findEvents($category) //$category has the searched value passed from the controller.
{
return $this->getEntityManager()->createQuery(
    'SELECT e FROM BackendBundle:Events e WHERE e.category=:category ORDER BY e.datetime ASC, e.hour ASC')
    ->setParameters(array(
        'category' => $category))
    ->getResult();
}

,但是现在我不知道如何仅与某些列的值相关联,例如此示例:

 $arr = array(array("title" => 'Example Title 1',"description" => "Description 1.","datetime"=>new DateTime("now")),
        array("title" => 'Example Title 2',"description" => "Description 1.","datetime"=>new DateTime("now"))
    );

终于感谢@garry,我能够通过以下代码解决我的问题:

public function findEvents($category) //$category has the  searched value passed from the controller.
{
  return $this->getEntityManager()->createQuery(
   'SELECT CONCAT(CONCAT(e.title, ' '), e.date) AS title, e.description, e.datetime FROM BackendBundle:Events e WHERE e.category=:category ORDER BY e.datetime ASC, e.hour ASC')
   ->setParameters(array(
    'category' => $category))
   ->getResult();
}

除了仅获取所需的三列的值外,我还能够将日期添加到标题中(我在问题之前没有提出)。

相关内容

  • 没有找到相关文章