我的2个实体之间的关系是OneToOne
关系。
1)用户实体:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
*/
class User
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var $userContact
*
* @ORM\OneToOne(targetEntity="UserContact" , inversedBy="User")
* @ORM\JoinColumn(name="id", referencedColumnName="user_id", nullable=false)
**/
private $userContact;
/**
* @ORM\Column(type="string", length=255)
*/
private $last_name;
public function getId()
{
return $this->id;
}
public function getLastName(): ?string
{
return $this->last_name;
}
public function setLastName(string $last_name): self
{
$this->last_name = $last_name;
return $this;
}
}
class UserContact
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id()
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="integer")
*/
private $user_id;
/**
* @ORM\OneToOne(targetEntity="User", inversedBy="UserContact")
*/
private $user;
/**
* @ORM\Column(type="string", length=255)
*/
private $mobile_number;
public function getId()
{
return $this->id;
}
public function getUserId(): ?int
{
return $this->user_id;
}
public function setUserId(int $user_id): self
{
$this->user_id = $user_id;
return $this;
}
public function getMobileNumber(): ?string
{
return $this->mobile_number;
}
public function setMobileNumber(string $mobile_number): self
{
$this->mobile_number = $mobile_number;
return $this;
}
}
我的用户存储库如下所示:
class UserRepository extends ServiceEntityRepository
{
public function index() {
return $this->createQueryBuilder('u')
->innerJoin('u.userContact', 'uc')
->getQuery()
->execute();
}
}
控制器看起来像这样:
public function index()
{
$users = $em->getRepository('App:User')->index();
}
它抛出了像这样的错误:
Missing value for primary key id on App\Entity\UserContact
答案 0 :(得分:2)
在您的关联中,拥有方为User
,反面为UserContact
。您必须使用mappedBy
代替inversedBy
。因此,用户实体中$user
属性的注释必须为:
/**
* @ORM\OneToOne(targetEntity="User", mappedBy="UserContact")
*/
private $user;