我正在使用symfony和php,我是新手。我希望回应所有用户的汽车。
class UserController extends Controller
{
public function indexAction($uname)
{
$cars = new cars();
$user = new user();
$models = new models();
$brands = new brands();
$a = 1;
$em = $this -> getDoctrine() -> getEntityManager();
$id = $em -> getRepository("OBCarsTest1Bundle:user") ->findOneByuname($uname);
array ($UserCars = $em -> getRepository("OBCarsTest1Bundle:cars") ->findByidUser($id));
//$ModelId = $em -> getRepository("OBCarsTest1Bundle:models")->findById($UserCars);
//$BrandsId = $em -> getRepository("OBCarsTest1Bundle:brands")->findOneById($ModelId);
while($UserCars[$a]->getId() != Null)
{
if(! isset($UserCars[$a]))
{
$UserCars[$a] = Null;
}
//i want to see all the cars of the users
echo ('Created user : '.$UserCars[$a]->getName());
//return new Response('Created user : '.$UserCars[$a]->getId());
$a++;
}
return new Response('ma akal');
//return $this->render('OBCarsTest1Bundle:Default:index.html.twig', array('UserCars' => $UserCars));
}
现在我的代码看起来像这样(在进行任何更改之前),但我遇到了错误:
注意:未定义的属性:OBCarsTest1Bundle \ Entity \ cars :: $ getName
我搜索了这个问题并尝试修复它并更改了代码,但我得到了相同的结果。
class UserController extends Controller
{
public function indexAction($uname)
{
$cars = new cars();
$user = new user();
$models = new models();
$brands = new brands();
$a = 0;
$em = $this -> getDoctrine();
$id = $em -> getRepository("OBCarsTest1Bundle:user") ->findOneByuname($uname);
$UserCars = $em -> getRepository("OBCarsTest1Bundle:cars") ->findByidUser($id);
//$ModelId = $em -> getRepository("OBCarsTest1Bundle:models")->findById($UserCars);
//$BrandsId = $em -> getRepository("OBCarsTest1Bundle:brands")->findOneById($ModelId);
foreach($UserCars as $car)
{
echo "$car->getName() <br>";
}
return new Response('ma akal');
//return $this->render('OBCarsTest1Bundle:Default:index.html.twig', array('UserCars' => $UserCars));
}
答案 0 :(得分:2)
这里有两个问题:
数组索引从0开始,您使用$a = 1;
,因此您可能错过了第一个元素;
您不应该使用while
循环遍历数组,因为当没有更多元素时,您将始终遇到问题/错误/警告,此循环以定义警告结束:
while($UserCars[$a]->getId() != Null)
相反,您应该使用foreach
循环来遍历每个元素:
foreach ($UserCars as $UserCar) {
// not sure if you need this, I would guess you don't:
if ($UserCar->getId() != Null) {
...
答案 1 :(得分:1)
重构您的代码以使用foreach
。如果您想要做的就是遍历汽车阵列并打印每辆车的名称,那么这应该可以胜任。我已经删除了那些不必说明这一点的内容。
class UserController extends Controller
{
public function indexAction()
{
$UserCars = array(...);
foreach ($UserCars as $Car) {
if (is_a($Car, 'UserCar')) {
echo ('Created user : ' . $Car->getName());
}
}
}
}
作为预防措施,您可能还需要做的是验证您迭代的每个$UserCar
的身份,以便在调用方法之前确保它符合您的想法。这就是is_a
方法的作用(我已经猜到了你的班级名称)。
答案 2 :(得分:1)
如果你真的想要while循环:
$count_cars = count($UserCars);
$i = 0;
while($count_cars > 0)
{
echo ('Created user : '.$UserCars[$i]->getName());
//return new Response('Created user : '.$UserCars[$a]->getId());
$count_cars--;
$i++;
}
没有必要检查汽车是否有Id,因为从您的存储库中获取它显然会有一个。 但是foreach更容易..不需要额外的变量($ i,$ count_cars)