【发布时间】:2011-07-27 17:00:29
【问题描述】:
背景/应用
我有两个数据库表,supplier 和 address 具有一对一的关系,因为并非所有供应商都有地址(这只是一个更大应用程序的简化示例)。我在 MySQL 数据库中使用 Doctrine ORM (1.2)。
我无法向没有地址的现有供应商添加地址。我可以修改已有供应商的地址,而该供应商确实有一个没有问题的供应商。
以下架构和四个简单脚本显示了流程的每个阶段发生的情况。
架构
Address:
columns:
id:
type: integer
primary: true
autoincrement: true
town: string(300)
Supplier:
columns:
id:
type: integer
primary: true
autoincrement: true
name: string(300)
address_id: integer
relations:
Address:
foreignType: one
脚本一:创建两个供应商,有地址和没有地址
$supplier = new Supplier();
$supplier->name = 'A supplier with an address';
$supplier->Address->town = 'A town';
$supplier->save();
$supplier = new Supplier();
$supplier->name = 'A supplier without an address';
$supplier->save();
脚本二:确认数据已保存
$supplier = Doctrine_Core::getTable('Supplier')->find(1);
var_dump($supplier->toArray());
$supplier = Doctrine_Core::getTable('Supplier')->find(2);
var_dump($supplier->toArray());
输出:
array
'id' => string '1' (length=1)
'name' => string 'A supplier with an address' (length=26)
'address_id' => string '1' (length=1)
array
'id' => string '2' (length=1)
'name' => string 'A supplier without an address' (length=29)
'address_id' => null
脚本三:获取和更新/创建地址
$supplier = Doctrine_Core::getTable('Supplier')->find(1);
$supplier->Address->town = 'A Different Town';
$supplier->save();
var_dump($supplier->toArray());
$supplier = Doctrine_Core::getTable('Supplier')->find(2);
$supplier->Address->town = 'A New Town';
$supplier->save();
var_dump($supplier->toArray());
输出:(注意,此时,它会建议该地址是为之前没有地址的第二个供应商创建的)
array
'id' => string '1' (length=1)
'name' => string 'A supplier with an address' (length=26)
'address_id' => string '1' (length=1)
'Address' =>
array
'id' => string '1' (length=1)
'town' => string 'A Different Town' (length=16)
array
'id' => string '2' (length=1)
'name' => string 'A supplier without an address' (length=29)
'address_id' => string '2' (length=1)
'Address' =>
array
'id' => string '2' (length=1)
'town' => string 'A New Town' (length=10)
脚本四:确认更改已保存
$supplier = Doctrine_Core::getTable('Supplier')->find(1);
var_dump($supplier->toArray());
$supplier = Doctrine_Core::getTable('Supplier')->find(2);
var_dump($supplier->toArray());
$address = Doctrine_Core::getTable('Address')->find(2);
var_dump($address->toArray());
输出:
array
'id' => string '1' (length=1)
'name' => string 'A supplier with an address' (length=26)
'address_id' => string '1' (length=1)
array
'id' => string '2' (length=1)
'name' => string 'A supplier without an address' (length=29)
'address_id' => null
array
'id' => string '2' (length=1)
'town' => string 'A New Town' (length=10)
谁能解释为什么第二个供应商的地址被插入到数据库中,但实际上并没有链接到供应商?
【问题讨论】:
标签: php orm doctrine relationship one-to-one