Getting Doctrine DQL results the SQL way

删除回忆录丶 提交于 2019-12-07 22:10:41

问题


When performing a DQL query such as:

SELECT u AS user, t AS transaction
FROM Model\User u
JOIN Model\Transaction t WITH t.user = u

You get alternating rows of results, such as:

  • ['user' => Model\User(1)]
  • ['transaction' => Model\Transaction(1)]
  • ['transaction' => Model\Transaction(2)]
  • ['user' => Model\User(2)]
  • ['transaction' => Model\Transaction(3)]
  • ['transaction' => Model\Transaction(4)]
  • ['transaction' => Model\Transaction(5)]

Is it possible to get the result the SQL way, like:

  • ['user' => Model\User(1), 'transaction' => Model\Transaction(1)]
  • ['user' => Model\User(1), 'transaction' => Model\Transaction(2)]
  • ['user' => Model\User(2), 'transaction' => Model\Transaction(3)]
  • ['user' => Model\User(2), 'transaction' => Model\Transaction(4)]
  • ['user' => Model\User(2), 'transaction' => Model\Transaction(5)]

It would be much easier to deal with than alternating objects.


回答1:


Unfortunately, there's no current easy way of achieve this. However, there's a way that you could get that result.

Create a class named UserTransactionDTO and accept 2 constructor arguments: User and Transaction.

Now rewrite your DQL query like this:

SELECT NEW UserTransactionDTO(user, transaction)
  FROM Model\User u
  JOIN Model\Transaction t WITH t.user = u

This should give you a result that matches your desired behavior (a list of UserTransactionDTO objects), allowing you to access both User and Transaction on a single record.




回答2:


The way I do it now is:

$query = $em->createQuery('
    SELECT u, t
    FROM Model\User u
    JOIN Model\Transaction t WITH t.user = u
');

$rows = $query->getResult();
$rowCount = count($rows);

$result = [];

for ($i = 0; $i < $rowCount; $i += 2) {
    /** @var Model\User $user */
    $user = $rows[$i];

    /** @var Model\Transaction $transaction */
    $transaction = $rows[$i + 1];

    $result[] = new UserTransactionDTO($user, $transaction);
}

return $result;

Which is clean enough.

Note that this example is a bad one, as you could only return Transactions and get the User from there; but I regularly encounter use cases where a single object does not hold all the information.



来源:https://stackoverflow.com/questions/37545979/getting-doctrine-dql-results-the-sql-way

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!