3

我有一个包含 3 列 EmployeeNum、JobTitleCode 和成本的表。我已经为它创建了一个具有基本 CRUD 功能的实体。

EmployeeNum 和 JobTitleCode 都是外键,当显示实体时,我希望能够查询数据库中的另一个表以从 EmployeeNum 中提取 EmployeeName,从 JobTitleCode 中提取 JobTitle。

在 Symfony 1.4 中,我可以通过在模式中定义 'Employees' 来执行 Doctrine_Core::getTable('Employees').find('EmployeeNum') 但我在 Symfony 2.4 中找不到任何类似的方法。

从 getDoctrine() 的API中,我没有找到任何可以使用的类似方法,如果我这样构建查询:

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

那么你如何去访问数据库中其他表的数据呢?

4

1 回答 1

3

默认情况下,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));

有用的链接:

于 2014-02-26T04:43:03.577 回答