Symfony3.4持有oneTomany实体

时间:2018-04-06 07:58:49

标签: symfony-3.4

我需要在symfony3.4中为一个应用程序聊天,所以我创建了一个通道实体和一个消息实体,我创建了一对多的关系,并在通道中添加了消息,但实体没有持久性包括在意图中。

在邮件实体

/* $channel.
*
* (Many-To-One, Unidirectional)
* @ORM\ManyToOne(targetEntity="Soraya\ChatBundle\Entity\chanEntity",inversedBy="messages")
* @ORM\JoinColumn(name="channel_id", referencedColumnName="id")
* 
*/
protected $channel;

public function setChannel(\Soraya\ChatBundle\Entity\chanEntity $channel ){
    $this->channel = $channel;
    return $this;
}

在ChanEntity实体

 /*
     * $messages
     * (One-To-Many, Bidirectional)
     * @ORM\OneToMany(targetEntity="Soraya\ChatBundle\Messages", mappedBy="channel"),cascade={"persist", "remove"})
     *
     *

     */
    protected $messages;

    public function __construct() {
        parent::__construct();
        $this->messages = new ArrayCollection();


    }

    public function addmessages(\Soraya\ChatBundle\Entity\Messages $message){

        $this->messages[]=$message;
        $message->setChannel($this);
        return $this;
    }

在我的控制器中

`public function addMessageAction(Request $request, $idChan, $utilisateur, $message){

$em = $this->getDoctrine()->getManager();

//message
$advertmess = new Messages();

$advertmess->setMessage($message);
$advertmess->setpseudoUtilisateur($utilisateur);

// chan


$advert2 =  $em->getRepository('ChatBundle:chanEntity')->find($idChan);
$advert2->addmessages($advertmess);

// entity

$em->persist($advert2);
$em->persist($advertmess);
$em->flush();



//$em->persist($advert);
//$em->flush();

var_dump($advert2);
//var_dump($advertmess);


return new Response("OK");

}`

When i saw the var_dump in the request i can see the entity inside the entity but when i try to access to it after there nothing :

我在chan

的var_dump中可以看到的例子
object(Soraya\ChatBundle\Entity\chanEntity)[790]
  protected 'messages' => null
  protected 'typesChan' => string 'contact' (length=7)
  .......

请求中填写

object(Soraya\ChatBundle\Entity\chanEntity)[849]
  protected 'messages' => 
    array (size=1)
      0 => 
        object(Soraya\ChatBundle\Entity\Messages)[838]
          protected 'pseudoUtilisateur' => string 'user' (length=16)
          protected 'message' => string 'testword' (length=5)
          protected 'channel' => 
            &object(Soraya\ChatBundle\Entity\chanEntity)[849]
          protected 'id' => int 135
          protected 'sync_uuid' => string '64373958-f69e-4b84-8543-aa3ed6b3be19' (length=36)
          protected 'isDeleted' => boolean false
          protected 'cree_le' =
          ......

我的实体内的实体不会持久存在,我可以访问在mydatabase中创建的消息,但不能访问chan和消息之间的连接。有人知道可能出现什么问题?谢谢。

1 个答案:

答案 0 :(得分:0)

我发现我的错误,在ORM JOIN中还需要一个*,它必须是那样的。

    /** $channel.
*
* (Many-To-One, Unidirectional)
* @ORM\ManyToOne(targetEntity="Soraya\ChatBundle\Entity\chanEntity",inversedBy="messages")
* @ORM\JoinColumn(name="channel_id", referencedColumnName="id")
* 
*/
protected $channel;