Home > Backend Development > PHP Tutorial > 如何理解Doctrine2里面的mappedBy和inversedBy???

如何理解Doctrine2里面的mappedBy和inversedBy???

WBOY
Release: 2016-06-06 20:43:22
Original
1676 people have browsed it

如何理解Doctrine2里面的mappedBy和inversedBy???

/** @Entity */
class Customer
{
// ...

<code>/**
 * @OneToOne(targetEntity="Cart", mappedBy="customer")
 */
private $cart;

// ...
</code>
Copy after login
Copy after login

}

/** @Entity */
class Cart
{
// ...

<code>/**
 * @OneToOne(targetEntity="Customer", inversedBy="cart")
 * @JoinColumn(name="customer_id", referencedColumnName="id")
 */
private $customer;

// ...
</code>
Copy after login
Copy after login

}

回复内容:

如何理解Doctrine2里面的mappedBy和inversedBy???

/** @Entity */
class Customer
{
// ...

<code>/**
 * @OneToOne(targetEntity="Cart", mappedBy="customer")
 */
private $cart;

// ...
</code>
Copy after login
Copy after login

}

/** @Entity */
class Cart
{
// ...

<code>/**
 * @OneToOne(targetEntity="Customer", inversedBy="cart")
 * @JoinColumn(name="customer_id", referencedColumnName="id")
 */
private $customer;

// ...
</code>
Copy after login
Copy after login

}

Doctrine是ORM;
ORM支持改变关联关系,如将小组的管理员由A变为B;
我们可以定义谁“拥有”这个关联关系,使关联就有了“方向”;
从而方便了逻辑和编码,即ORM只用检查“拥有”关联关系的对象上关联的变化(如小组的管理员现在是A还是B?)。

有inversedBy的,是“拥有”关联关系的一侧。

你贴出的代码中,

Customer与Cart之间的“谁的购物车”的关联关系,是由Cart拥有;在Customer对象上,改变其cart变量,通过Doctrine保存,并不会导致购物车易主。

以上,都是指不写额外代码,靠Doctrine自动识别的情形。

Customer 和 Cart 關聯起來

兩邊都可以簡單地調用對方

<code class="lang-php">/**
 * 從Customer中取得Cart的資料
 *
 * @var Cart $cart
 */
$cart = $customer->getCart();

/**
 * 從Cart中取得Customer的資料
 *
 * @var Customer $customer
 */
$customer = $cart->getCustomer();
</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template