gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:08:57 26 4
gpt4 key购买 nike

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

Warning: Invalid argument supplied for 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;
}
}

Controller

   $city=new City();

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

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

索引 Controller

 public function indexAction()
{

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

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

Warning: Invalid argument supplied for foreach()

User.php

foreach ($this->cities as $city)

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

感谢您的帮助。

编辑:已解决

I have to update my CityBundle\Resources\config\doctrine\City.orm.yml file

最佳答案

在你的 City 类中,不应该是这样的关系:

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

连接列不应该是用户表的id。

然后,当然:

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

关于Symfony,oneToMany 关系 为 foreach() 提供的参数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27509986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com