我将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));
}
当我尝试在视图中显示数组(城市)时出现错误
User.php 中的警告:为foreach()提供的参数无效
foreach($ this-&gt; cities as $ city)
我的表城市外观(id,名称)
感谢您的帮助。
编辑:已解决
我必须更新我的CityBundle \ Resources \ config \ doctrine \ City.orm.yml文件
答案 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;
}