1

我有 2 个实体,用户和客户,具有 OneToOne 双向关系。用户实体也与发票实体有双向关系:

class User implements UserInterface
{
    /**
     * @ORM\OneToOne(targetEntity="Evo\UserBundle\Entity\Customer", mappedBy="user", cascade={"persist", "remove"})
     * @Type("Evo\UserBundle\Entity\Customer")
     */
    protected $customer;

    /**
     * @ORM\OneToMany(targetEntity="Evo\BackendBundle\Entity\Invoice", mappedBy="user", cascade={"remove"})
     */
    protected $invoices;
}

class Customer
{
    /**
     * @ORM\OneToOne(targetEntity="Evo\UserBundle\Entity\User", inversedBy="customer")
     * @ORM\JoinColumn(name="account", nullable=false)
     */
    protected $user;
}

现在,我想使用 NativeQuery 和 ResultSetMapping 检索用户及其客户关系,仅此而已。我试过了

$sql = "SELECT a.id, a.identifier, c.id AS customer_id, c.email, c.firstname, c.lastname
    FROM account a
    INNER JOIN customer c ON c.account = a.id
    WHERE c.email = 'user@mail.com'";

$rsm = new ResultSetMapping();
$rsm->addEntityResult('Evo\UserBundle\Entity\User', 'u');
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'identifier', 'username');

$rsm->addJoinedEntityResult('Evo\UserBundle\Entity\Customer' , 'c', 'u', 'customer');
$rsm->addFieldResult('c', 'customer_id', 'id');
$rsm->addFieldResult('c', 'email', 'email');
$rsm->addFieldResult('c', 'firstname', 'firstname');
$rsm->addFieldResult('c', 'lastname', 'lastname');

$query = $this->_em->createNativeQuery($sql, $rsm);

$users = $query->getResult();

return $users;

但这会返回用户,以及他所有的双向关系:

array(1) {
  [0]=>
  object(stdClass)#1370 (33) {
    ["__CLASS__"]=>
    string(26) "Evo\UserBundle\Entity\User"
    ["id"]=>
    string(5) "38425"
    ["invoices"]=>
    array(77) {
      [0]=>
      string(32) "Evo\BackendBundle\Entity\Invoice"
      [1]=>
      string(32) "Evo\BackendBundle\Entity\Invoice"
      [2]=>
      string(32) "Evo\BackendBundle\Entity\Invoice"
      [3]=>
      string(32) "Evo\BackendBundle\Entity\Invoice"
      [4]=>
      string(32) "Evo\BackendBundle\Entity\Invoice"
      [5]=>
      string(32) "Evo\BackendBundle\Entity\Invoice"
      [6]=>
      string(32) "Evo\BackendBundle\Entity\Invoice"
      [7]=>
      string(32) "Evo\BackendBundle\Entity\Invoice"
      [8]=>
      string(32) "Evo\BackendBundle\Entity\Invoice"
      [9]=>
      string(32) "Evo\BackendBundle\Entity\Invoice"
    }
    ["customer"]=>
    object(stdClass)#3083 (87) {
      ["__CLASS__"]=>
      string(30) "Evo\UserBundle\Entity\Customer"
      ["id"]=>
      string(5) "38553"
      ["user"]=>
      string(26) "Evo\UserBundle\Entity\User"
      ["email"]=>
      string(12) "rien@rien.fr"
      ["lastname"]=>
      string(13) "RAVIER (TEST)"
      ["firstname"]=>
      string(7) "Jacques"
    }
    ["username"]=>
    string(12) "rien@rien.fr"
  }
}

我想在返回的数据中去掉这些 Invoice 关系。我应该对 ResultSetMapping 做些什么?

注意:由于特定原因,我不能在此功能上使用经典 DQL,我确实需要使用 NativeQuery。

4

0 回答 0