gpt4 book ai didi

php - 一对多关系删除 Doctrine 中的外键

转载 作者:搜寻专家 更新时间:2023-10-30 20:54:49 25 4
gpt4 key购买 nike

这让我发疯。

一个Client 可以有多个Vehicle

这是一对多的关系。尝试保存实体时,我收到一条错误消息,指出外键为空。当我删除 Doctrine 关系并单独存储 Vehicle 时,一切正常。

这就是我创建关系的方式:

class Vehicle {

...

/**
* @ORM\ManyToOne(targetEntity="Client", inversedBy="vehicles")
* @ORM\JoinColumn(name="client_id", referencedColumnName="id")
*/
public $client;

}

class Client {

...

public function __construct()
{
parent::__construct();
$this->vehicles = new \Doctrine\Common\Collections\ArrayCollection();
}


/**
* @ORM\OneToMany(targetEntity="Vehicle", mappedBy="client", cascade={"persist"})
*/
private $vehicles;

}

我尝试像这样保存实体:

$client = new Client();
$vehicle = new Vehicle();
$client->getVehicles()->add($vehicle);
$em->persist($client);
$em->flush();

接下来,我收到一个 PDO 异常,指出 Vehicle 表上的 client_id 不能为 null

似乎 Doctrine 没有正确复制外键。

我做错了什么?

最佳答案

根据 their docs :

It is not possible to use join columns pointing to non-primary keys.

Doctrine will think these are the primary keys and create lazy-loading proxies with the data, which can lead to unexpected results. Doctrine can for performance reasons not validate the correctness of this settings at runtime but only through the Validate Schema command.

显然,您需要一种不同的方法。

他们的例子中给出了一个解决方案:

CREATE TABLE product (
id INTEGER,
name VARCHAR,
PRIMARY KEY(id)
);
CREATE TABLE product_attributes (
product_id INTEGER,
attribute_name VARCHAR,
attribute_value VARCHAR,
PRIMARY KEY (product_id, attribute_name)
);

This schema should be mapped to a Product Entity as follows:

class Product
{
private $id;
private $name;
private $attributes = array();
}

Where the attribute_name column contains the key and attribute_value contains the value of each array element in $attributes.

关于php - 一对多关系删除 Doctrine 中的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26891143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com