将计算列添加到DataTable

时间:2019-01-16 18:54:52

标签: doctrine-orm datatables symfony4

我正在使用Symfony4,Doctrine2和DataTables。我想通过我自己的 QueryBuilderProcessorInterface 显示来自实体的数据的表,但是我遇到了计算列的问题。

我的数据表定义:

$table = $dataTableFactory->create()
        ->add('date', DateTimeColumn::class)
        ->add('event', TextColumn::class)
        ->add('eventType', TextColumn::class, ['field' => 'et.name'])
        ->add('beverage', TextColumn::class, ['field' => 'b.name'])
        ->add('beverageType', TextColumn::class, ['field' => 'bt.name'])
        ->add('alcohol', TextColumn::class, ['field' => 'b.alcoholVolume'])
        ->add('glassVolume', TextColumn::class, ['field' => 'v.volume'])
        ->add('numberOfGlasses', TextColumn::class)
        ->add('totalVolume', TextColumn::class)
        ->add('alcoholVolume', TextColumn::class)
        ->createAdapter(ORMAdapter::class, [
            'entity' => DiaryItem::class,
            'query' => [$diaryItemRepository]]
        )
        ->handleRequest($request);

最后两列 totalVolume alcoholVolume 不是实体的一部分,它们是经过计算的。我的 QueryBuilder 看起来像

/**
 * @param QueryBuilder $qb
 * @param DataTableState $state
 * @return void
 */
public function process(QueryBuilder $qb, DataTableState $state)
{
    $qb
        ->select(
            'i',
            'i.numberOfGlasses * v.volume AS totalVolume',
            'i.numberOfGlasses * v.volume * b.alcoholVolume / 100 AS alcoholVolume'
        )
        ->from(DiaryItem::class, 'i')
        ->join('i.eventType', 'et')
        ->join('i.beverage', 'b')
        ->join('b.type', 'bt')
        ->join('i.glassVolume', 'v');
}

但是,如果我通过上面的 QueryBuilder 填充DataTable,则会出现错误

Cannot read property "diaryItemId" from an array. Maybe you intended to write the property path as "[diaryItemId]" instead.

我认为问题在于,如果我添加了两个计算列,则QueryBuilder结果中的主要实体 DiaryItem 已移至索引 0 ,请参见

AbstractAdapter.php on line 53:
array:3 [
    0 => DiaryItem {#677
        -diaryItemId: 1
        -date: DateTime @1546815600 {#566
        date: 2019-01-07 00:00:00.0 Europe/Berlin (+01:00)
    }
    -event: "Kurty"
    -eventType: EventType {#710
      +__isInitialized__: false
      -eventTypeId: 7
      -name: null
       …2
    }
    -beverage: Beverage {#720
      +__isInitialized__: false
      -beverageId: 1
      -name: null
      -alcoholVolume: null
      -type: null
       …2
    }
    -numberOfGlasses: 3
    -glassVolume: Volume {#725
      +__isInitialized__: false
      -volumeId: 30
      -volume: null
       …2
    }
  }
  "totalVolume" => "1500"
  "alcoholVolume" => "61.500000"
]

是否有解决方案来添加两个计算列?我不想将它们添加到实体DiaryItem中,因为我希望通过它们进行过滤/排序。预先非常感谢。

0 个答案:

没有答案