问题描述
我想用重复的选项创建ManyToMany关系.一个用户可以拥有许多CAR,而许多CAR可以属于不同的用户.同时,一个用户可以拥有许多相同类型的汽车.
I want to create ManyToMany relation with duplicate options. One USER can have many CARS and many CARS can belong to various USERs. At the same time, one USER can own many cars of the same type.
我该如何在Symfony 4和《学说》中解决这个问题?
How do I solve this in Symfony 4 and Doctrine?
推荐答案
假定您有两个实体,如User
和Car
所述,并在它们之间定义了ManyToMany
关系.看起来可能像这样:
Presumably you have two entities, as described, User
and Car
, and define a ManyToMany
relation between them. It could look like this:
User.php
User.php
class User
{
// ...
/**
* @ManyToMany(targetEntity="App\Entity\Car", inversedBy="users")
*/
private $cars;
// ...
}
Car.php
Car.php
class Car
{
// ...
/**
* @ManyToMany(targetEntity="App\Entity\User", mappedBy="cars")
*/
// ...
private $users;
}
Doctrine将自动在它们之间创建一个中间表,类似于带有两列的users_cars
:user_id
和car_id
.它们将分别持有users
和cars
的外键.您的问题是,Doctrine创建了这两列的复合主键,这意味着它必须是唯一的,并且您不能有以下内容:
Doctrine will automatically create an intermediate table between them, something like users_cars
with two columns: user_id
and car_id
. They will hold the foreign keys to users
and cars
respectively. Your problem is that Doctrine creates a composite primary key of these two columns, which means it must be unique and you can't have something like:
user_id | car_id
------------------
1 | 1
1 | 1
例如应该是这样:
Konrad | Porsche 911
Konrad | Porsche 911
换句话说,康拉德有两辆相同型号的汽车.
With other words, Konrad has two cars of the same model.
您可以将ManyToMany
关系分为两个ManyToOne
并为中间表定义自己的实体:
You could break the ManyToMany
relation into two ManyToOne
and define your own entity for the intermediate table:
Ownership.php
Ownership.php
class Ownership
{
// ...
/**
* @ManyToOne(targetEntity="App\Entity\User", inversedBy="cars_owned")
*/
private $user;
/**
* @ManyToOne(targetEntity="App\Entity\Car", inversedBy="owners")
*/
private $car;
// ...
}
在User
和Car
中设置适当的OneToMany
关系.现在,您可以在表ownerships
中具有重复项.这使您可以灵活地添加有关所有权的更多信息,例如用户购买汽车时的购买日期.
Set up the appropriate OneToMany
relations in User
and Car
. Now you can have duplicates in your table ownerships
. This gives you the flexibility to add more information about the ownership, maybe purchase date when the user has acquired the car.
我想强调一下,命名是编程中最重要的事情之一.事先考虑一下,为您的类和方法命名.他们描述什么,他们做什么?
I'd like to stress that naming is one of the most important things in programming. Name your classes and methods with some forethought. What to they describe, what do they do?
在我看来,用户如何拥有一次以上的同一辆汽车并不是立即显而易见的.我当时用汽车"一词来思考一辆物理车辆.也许您应该将该实体称为CarModel
或CarBrand
.同样,User
不是很直观,我宁愿选择Owner
或Person
,但这取决于您应用程序的进一步业务逻辑.
To me it wasn't immediately obvious how a user can own the same car more then once. I was thinking of a physical vehicle by the term car. Maybe you should rather call that entity CarModel
or CarBrand
. Also User
isn't very intuitive, I'd rather choose Owner
or Person
, but this depends on the further business logic of your application.
这篇关于允许Symfony 4和Doctrine复制重复的ManyToMany关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!