默认情况下,Doctrine 总是尝试将您的结果映射到实体。
您可以使用准备好的语句而无需提供结果映射:
获取连接:
$connection = $em->getConnection();
准备一个语句并执行它:
$statement = $connection->prepare(
'SELECT a FROM hs_hr_employee a WHERE a.emp_number = :emp'
);
$statement->bindValue('emp', $emp);
$statement->execute();
// for SELECT queries
$result = $statement->fetchAll('EAGER'); // note: !== $connection->fetchAll()!
// for INSERT, UPDATE, DELETE queries
$affected_rows = $statement->rowCount();
这很有表现力。有关较短的变体,请参见下面的示例。
选择:
使用带有结果映射的Native SQL 查询。
高级示例显示如何重命名结果数组中的列。
// create a result-mapping
$rsm = new ResultSetMapping;
$rsm->addScalarResult('n', 'nickname');
$rsm->addScalarResult('f', 'muchachos');
$query = $em->createNativeQuery(
'
SELECT
users.name as n
COUNT(user.friends) as f
WHERE
users.name = :username_parameter
FROM
user_table_name users
',
$rsm
);
$query->setParameter('username_parameter', $username);
$result = $query->getSingleResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
// example: $username = 'nifr'
// array => [
// 'nickname' => 'nifr'
// 'muchachos' => 3919410
// ]
较短的版本:(让教义准备语句+直接获取结果)
// for SELECT queries
$result = $connection->executeQuery(
'SELECT a FROM hs_hr_employee a WHERE a.emp_number = ?'
array($emp)
);
//for INSERT, UPDATE, DELETE queries
$affected_rows = $connection->executeUpdate(
'DELETE FROM hs_hr_employee a WHERE a.emp_number = ?',
array($emp)
);
// fetch all into array ( <numeric-index> => <associative-array-entry> )
$connection->fetchAll(
'SELECT a FROM hs_hr_employee a WHERE a.emp_number = ?',
array($emp)
);
// fetch only first-row of result-set as associative array
$connection->fetchAssoc(
'SELECT a FROM hs_hr_employee a WHERE a.emp_number = ?',
array($emp)
);
// fetch only first-row of result-set as array with numeric indexes
$connection->fetchArray(
'SELECT a FROM hs_hr_employee a WHERE a.emp_number = ?',
array($emp)
);
甚至更短的变体(对于 INSERT、UPDATE 或 DELETE 查询)
// DELETE FROM user WHERE id = ? (1)
$conn->delete('user', array('id' => 1));
// INSERT INTO user (username) VALUES (?) (nifr)
$conn->insert('user', array('username' => 'nifr'));
// UPDATE user (username) VALUES (?) WHERE id = ? (nifr, 1)
$conn->update('user', array('username' => 'nifr'), array('id' => 1));
有用的链接: