Symfony,oneToMany关系为foreach()提供的参数无效

时间:2014-12-16 17:03:00

标签: symfony foreach one-to-many

我将oneToMany关系添加到数据库,并且它正在工作,但是当我想查看数组时,我收到此错误:

  

警告:为foreach()提供的参数无效

这是我的 User.php

class User implements AdvancedUserInterface, \Serializable
{

 // ...
/**
 * @ORM\OneToMany(targetEntity="Acme\CityBundle\Entity\City", mappedBy="user")
 **/
private $cities;

  public function __construct()
{
    $this->cities = new ArrayCollection();
}

 /**
 * @inheritDoc
 */
public function getCities()
{
  $c = array();

foreach ($this->cities as $city) {
    $c[] = $city->getCity();
}
    return $c;
}

/**
 * Add cities
 *
 * @param \Acme\CityBundle\Entity\City $cities
 * @return User
 */
public function addCity(\Acme\CityBundle\Entity\City $city)
{
    $city->setUser($this);
    $this->cities->add($city);

    return $this->cities;
}

City.php

<?php

namespace Acme\CityBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * City
 */
class City
{
/**
 * @var integer
 */
private $id;

/**
 * @var string
 */
private $name;

 /**
 * @ManyToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="cities")
 * @JoinColumn(name="id", referencedColumnName="id")
 **/
private $user;

public function setUser($user)
{
    $this->user = $user;

    return $this;
}


/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Set name
 *
 * @param string $name
 * @return City
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

public function getCity()
{
    return $this;
}

/**
 * Get name
 *
 * @return string 
 */
public function getName()
{
    return $this->name;
}
}

控制器

   $city=new City();

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

   $city->setName('Miasto');
   $user->addCity($city);
   $em->persist($city);
   $em->persist($user);
   $em->flush();

索引控制器

 public function indexAction()
{

$cities=$this->get('security.context')->getToken()->getUser()->getCities();
 return $this->render(
        'AcmeUserBundle:User:index.html.twig',array( 'cities'=>$cities));
}

当我尝试在视图中显示数组(城市)时出现错误

  

警告:为foreach()提供的参数无效

User.php

中的

  

foreach($ this-&gt; cities as $ city)

我的表城市外观(id,名称)

感谢您的帮助。

编辑:已解决

  

我必须更新我的CityBundle \ Resources \ config \ doctrine \ City.orm.yml文件

1 个答案:

答案 0 :(得分:1)

在你的城市课堂上,不应该是这样的关系:

 /**
 * @ManyToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="cities")
 * @JoinColumn(name="cityId", referencedColumnName="id")
 **/
private $user;

join列不应该是用户表的id。

然后,当然:

public function getCities()
{
    return $this->cities;
}