我当前的客户实体有一个卸载区和一个装载区,它们都是ClientArea-Entities。
namespace ACME\DemoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Sorien\DataGridBundle\Grid\Mapping as GRID;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* ACME\DemoBundle\Entity\Client
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="ACME\DemoBundle\Entity\ClientRepository")
*/
class Client
{
/**
* @ORM\OneToMany(targetEntity="ClientArea",mappedBy="client", cascade={"persist", "remove"})
*/
public $unloading_areas;
/**
* @ORM\OneToMany(targetEntity="ClientArea",mappedBy="client", cascade={"persist", "remove"})
*/
public $loading_areas;
}
class ClientArea
{
/**
* @ORM\ManyToOne(targetEntity="Client")
*/
public $client;
}
这不起作用,因为客户端只能映射1个关联。
如何正确映射关系?
最佳答案
要创建实体关系,需要在连接表时使用键。您的Client类应定义一个id
键,您需要初始化集合,如下所示:
class Client
{
//....
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORM\OneToMany(targetEntity="ClientArea", mappedBy="client", cascade={"persist", "remove"})
*/
public $unloading_areas;
/**
* @ORM\OneToMany(targetEntity="ClientArea", mappedBy="client", cascade={"persist", "remove"})
*/
public $loading_areas;
public function __construct() {
// Initialize collections
$this->unloading_areas = new \Doctrine\Common\Collections\ArrayCollection();
$this->loading_areas = new \Doctrine\Common\Collections\ArrayCollection();
}
// ....
}
然后,您的ClientArea类应如下所示:
class ClientArea
{
// ....
/**
* @ORM\Column(name="client_id", type="int", nullable=false)
*/
private $clientId;
/**
* @ORM\ManyToOne(targetEntity="Client")
* @JoinColumn(name="client_id", referencedColumnName="id")
*/
public $client;
// ....
}
现在,应该正确映射这两个实体。
要了解有关Doctrine中的关联映射的更多信息,请阅读此处的文章:http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/association-mapping.html
希望这可以帮助。
关于doctrine - Symfony2/Doctrine2一对多相同对象两次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9822553/