Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert user_id with ManyToOne relationship in symfony?

Tags:

php

mysql

symfony

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;
like image 641
hammies Avatar asked Oct 17 '25 04:10

hammies


1 Answers

$en->setUser($User); // $User is object

OR

$en->setUser($em->getReference('User\Bundle\RegisterBundle\Entity\User', $user_id)); // $user_id is integer, $em is EntityManager
like image 101
Evgeniy Budanov Avatar answered Oct 19 '25 20:10

Evgeniy Budanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!