【发布时间】:2014-12-16 17:03:00
【问题描述】:
我正在将 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->cities as $city)
我的餐桌城市外观(id,name)
感谢您的帮助。
编辑:已解决
我必须更新我的 CityBundle\Resources\config\doctrine\City.orm.yml 文件
【问题讨论】:
-
你的 $this->cities 有什么价值吗?
-
没有,但应该有
标签: symfony foreach one-to-many