我在Symfony中有一对多的关系。因此,我建立自己的班次管理,为多个用户创建事件。
当我保存一个事件到数据库我得到user_id null,我不会保存它的登录用户,我想保存多个用户的事件。
所以我不想保存user_id的用户,我想保存事件,在var_dump我得到用户的用户id,但当它保存我得到null在我的数据库中。有人知道怎么解决这个问题吗?
类用户:
class User implements AdvancedUserInterface, 'Serializable
{
/**
* @ORM'OneToMany(targetEntity="App'ShiftBundle'Entity'Shift", mappedBy="users", cascade={"all"})
*/
private $shifts;
public function __construct()
{
$this->isActive = true;
$this->isBlocked = false;
$this->shifts = new 'Doctrine'Common'Collections'ArrayCollection();
}
/**
* Add shifts
*
* @param 'App'ShiftBundle'Entity'Shift $shifts
* @return User
*/
public function addShift('App'ShiftBundle'Entity'Shift $shifts)
{
$this->shifts[] = $shifts;
$shifts->setUsers($this);
return $this;
}
/**
* Remove shifts
*
* @param 'App'ShiftBundle'Entity'Shift $shifts
*/
public function removeShift('App'ShiftBundle'Entity'Shift $shifts)
{
$this->shifts->removeElement($shifts);
}
/**
* Get shifts
*
* @return 'Doctrine'Common'Collections'Collection
*/
public function getShifts()
{
return $this->shifts;
}
}
类转变
class Shift
{
/**
* Set userId
*
* @param integer $userId
* @return Shift
*/
public function setUserId($userId)
{
$this->user_id = $userId;
return $this;
}
/**
* Get userId
*
* @return integer
*/
public function getUserId()
{
return $this->user_id;
}
/**
* @ORM'ManyToOne(targetEntity="App'AuthBundle'Entity'User", inversedBy="shifts")
* @ORM'JoinColumn(name="user_id", referencedColumnName="id")
*/
private $users;
/**
* Set users
*
* @param 'App'AuthBundle'Entity'User $users
* @return Shift
*/
public function setUsers('App'AuthBundle'Entity'User $users)
{
$this->users = $users;
return $this;
}
/**
* Get users
*
* @return 'App'AuthBundle'Entity'User
*/
public function getUsers()
{
return $this->users;
}
}
控制器public function createShiftTimeAction(Request $request)
{
$content = $request->getContent();
$json = json_decode($content);
$repository = $this->getDoctrine()->getRepository('AppShiftBundle:Shift');
$shift = new Shift();
var_dump($json->user_id);
$shift->setDay($json->day);
$shift->setMonth($json->month);
$shift->setYear($json->year);
$shift->setTimeFrom($json->time_from);
$shift->setTimeTo($json->time_to);
$shift->setUserId($json->user_id);
$em = $this->getDoctrine()->getManager();
$em->persist($shift);
$em->flush();
return new JsonResponse($json);
}
不应该给实体分配id。使用ORM(任何,不仅仅是Doctrine)时,你不应该操作id,而应该操作对象和模型。
所以,永远不要写$shift->setUserId($json->user_id);
应该改成
$shift->setUser($userRepository->find($json->user_id));
您正在使用对象关系模型,这意味着您需要通过对象和模型进行工作。
$shift->setUser($userRepository->find($json->user_id));