我正在尝试在symfony 4中使用ManyToOne。 这是我的搜索实体,
<?php
namespace App\Entity;
use App\Model\BaseCar;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
use Swagger\Annotations as SWG;
use JMS\Serializer\Annotation\Groups;
/**
* @ORM\Entity(repositoryClass="App\Repository\CarRepository")
* @ORM\Table(name="search")
* @UniqueEntity("id")
*/
class Search extends BaseCar
{
/**
* @ORM\ManyToOne(targetEntity="App\Entity\AdminUser",cascade={"refresh","merge"}, inversedBy="search")
* @ORM\JoinColumn(nullable=false)
*/
protected $user;
public function getUser()
{
return $this->user;
}
public function setUser($user)
{
$this->user = $user;
return $this;
}
}
这是我的AdminUser实体。
<?php
namespace App\Entity;
use App\Model\BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass="App\Repository\AdminUserRepository")
* @UniqueEntity("username")
*/
class AdminUser extends BaseUser
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @Assert\Email
* @ORM\Column(type="string", length=190, unique=true)
*/
protected $username;
/**
* @ORM\Column(type="string", length=190)
*/
protected $password;
/**
* @ORM\Column(type="string", length=190, nullable=true)
*/
protected $salt;
/**
* @ORM\Column(type="array")
*/
protected $roles;
/**
* @ORM\Column(type="string", length=190)
*/
protected $displayName;
/**
* @ORM\Column(type="string", length=190, nullable=true)
*/
protected $token;
/**
* @ORM\Column(type="string", length=190, nullable=true)
*/
protected $phoneNumber;
/**
* AdminUser constructor.
*/
public function __construct($username = null, array $roles = array(self::ROLE_ADMIN) , $password = null,$displayName=null,$phoneNumber = null, $salt=null)
{
parent::__construct($username, $roles,$password,$displayName,$phoneNumber, $salt);
}
}
当我尝试这个
$entityManager = $this->getDoctrine()->getManager();
$search = new Search();
$search->setType('jhkh');
$search->setUser(1);
$entityManager->persist($search);
$entityManager->flush();
但我却收到此错误,
关联字段的类型为“ App \ Entity \ AdminUser”的预期值 “ App \ Entity \ Search#$ user”,而是“ integer”。
答案 0 :(得分:1)
您可以尝试
$user = $entityManager->getRepository(AdminUser::class)->find(1);
$search->setUser($user);