Php 如何访问数据库中的不同表而不在Symfony中创建实体

Php 如何访问数据库中的不同表而不在Symfony中创建实体,php,symfony,doctrine,symfony-2.4,Php,Symfony,Doctrine,Symfony 2.4,我有一个包含3列EmployeeNum、JobTitleCode和cost的表。我为它制作了一个具有基本CRUD函数的实体 EmployeeNum和JobTitleCode都是外键,在显示实体时,我希望能够查询数据库中的另一个表,以从EmployeeNum提取EmployeeName,从JobTitleCode提取JobTitle 在Symfony 1.4中,我可以通过在模式中定义“Employees”来执行Doctrine_Core::getTable(“Employeens”)。查找(“Em

我有一个包含3列EmployeeNum、JobTitleCode和cost的表。我为它制作了一个具有基本CRUD函数的实体

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

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

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

createQuery('selecta FROM hs\u hr\u emp\u number=1的员工a')

我得到下面的错误

[Semantical Error] line 0, col 14 near 'hs_hr_employee': Error: Class 'hs_hr_employee' is not defined

那么,如何访问数据库中其他表中的数据呢

默认情况下,条令始终尝试将结果映射到实体

您可以使用,而无需提供结果映射:

获取连接:

$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();

准备语句并执行它:

$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();
这很有表现力。有关较短的变体,请参见下面的示例


备选方案:

$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();
使用带有结果映射的

高级示例演示如何重命名结果数组中的列

// 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
// ]

较短版本:(让条令编写语句+直接获取结果)


有用链接:

  • 语句(接口)
  • 语句(接口)

太棒了。非常感谢。