php-如何在不创建Symfony中实体的情况下访问数据库中的不同表
作者:互联网
我有一个包含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的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
那么,如何从数据库中的其他表访问数据呢?
解决方法:
在默认情况下,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)
);
甚至更短的变体(用于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));
有用的链接:
> Using prepared statement
> Native SQL
>声明(界面)API doc
>声明(界面)Code
标签:symfony,doctrine,symfony-2-4,php 来源: https://codeday.me/bug/20191122/2056711.html