Really new with symfony, coming from yii.
I can't insert user_id into another table with a ManyToOne relationship. When I get entity of the table that I want to insert of the id, I used: $en->setUser($user_id);
The outcome is: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null
but when I do var_dump($user_id);
there is an id. So how can I insert user_id with a many to one relationship?
[update] TableUser Entity
<?php
namespace User\Bundle\RegisterBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*
* @ORM\Table(name="user", indexes={@ORM\Index(name="user_id", columns={"user_id"})})
* @ORM\Entity
*/
class User
{
/**
* @var integer
*
* @ORM\Column(name="user_id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $userId;
public function getUserId()
{
return $this->userId;
}
}
?>
TableSomeModel Entity that has ManytoOne relationship with user_id
<?php
namespace \Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* SomeModel
*
* @ORM\Table(name="SomeModel", indexes={@ORM\Index(name="user_id", columns={"user_id"})})
* @ORM\Entity
*/
class SomeModel
{
/**
* @var \User
*
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* })
*/
private $user;
/**
* Set user
*
* @param \Entity\User $user
* @return App
*/
public function setUser(\Entity\User $user)
{
return $this->user;
}
/**
* Get user
*
* @return \Entity\User
*/
public function getUser()
{
return $this->user;
}
}
In the controller
$en = new SomeModel();
var_dump($user_id); //not null
$en->setUser($user_id); //always null;
$en->setUser($User); // $User is object
要么
$en->setUser($em->getReference('User\Bundle\RegisterBundle\Entity\User', $user_id)); // $user_id is integer, $em is EntityManager
Make sure that you have defined the relation properly. If you are using yml configuration files for defining entities, many to one relations are configured as given below.
manyToOne:
user:
targetEntity: Your\NameSpace\Entity\User
joinColumn:
name: user_id
referencedColumnName: id
If you are using annotation to define the relation,
/**
* @ManyToOne(targetEntity="Your\NameSpace\Entity\User")
* @JoinColumn(name="user_id", referencedColumnName="id")
**/
private $user;
And the setUser method in your entity
/**
* Set user
*
* @param Blsk\CoreBundle\Entity\User $user
*/
public function setUser(Your\NameSpace\Entity\User $user = null)
{
$this->user = $user;
}
EDIT In your code, setUser
method is not setting the user but returning the user.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.