我有一个包含3列EmployeeNum,JobTitleCode和cost的表。我已经为它创建了一个具有基本CRUD功能的实体。
EmployeeNum和JobTitleCode都是外键,在显示实体时,我希望能够查询数据库中的另一个表,从EmployeeNum中提取EmployeeName,从JobTitleCode中提取JobTitle。
在Symfony 1.4中,我可以通过在模式中定义'Employees'来查找Doctrine_Core :: getTable('Employees')。find('EmployeeNum')但我在Symfony 2.4中找不到任何类似的方法。
从API for getDoctrine()我找不到任何类似的方法我可以使用,如果我构建一个查询:
createQuery('SELECT a FROM hs_hr_employee a WHERE a.emp_number=1')
我收到以下错误
[Semantical Error] line 0, col 14 near 'hs_hr_employee': Error: Class 'hs_hr_employee' is not defined
那么如何从数据库中的其他表访问数据呢?
答案 0 :(得分:3)
默认情况下,Doctrine始终会尝试将结果映射到实体。
您可以使用 prepared statement 而无需提供结果映射:
获取连接:
$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 query 与结果映射一起使用。
高级示例显示如何重命名结果数组中的列。
// 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)
);
更短的变种( for 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));
有用的链接: