从Symfony中的数据库中获取对象

我有实体Domain,其中包含字段ID,域,用户 在现场用户中,我有一个ID,它是创建该域的用户的ID。

现在我已经在模板中创建了 ,该模板将显示用户创建的每个域。

我以某种方式弄乱了它,我不知道如何解决。

workspaces.html.twig

{% for domain in workspaces %}
    <div class="workspace card">
        <div class="card-body">
            <h4 class="card-title">{{workspaces.number}}</h4>
            <a href="/project" class="card-link">Card link</a>
        </div>
    </div>
    {% endfor %}

MainController.php

public function show()
{
    //todo: show domains for current user
    $repository = $this->getDoctrine()->getRepository(Domain::class);

    $currentUser = $this->getUser()->getID();
    $workspaces = $this->getDoctrine()
        ->getRepository(Domain::class)
        ->findByUsers($currentUser);
    return $this->render('workspaces.html.twig',array('workspaces' => $workspaces));
}

DomainRepository.php

/**
 * @param $currentUser
 * @return Domain[] Returns an array of Domain objects
*/

public function findByUsers($currentUser)
{
    return $this->createQueryBuilder('d')
        ->andWhere('d.users = :val')
        ->setParameter('val',$currentUser)
        ->orderBy('d.id','ASC')
        ->setMaxResults(15)
        ->getQuery()
        ->getResult();
}

我得到的错误:键为“ 0、1”的数组的键“域”不存在。 当前,我在数据库中有2条记录,但是当我添加更多记录时,错误显示更多键“ 0、1、2 ...”

我知道我某种程度上搞砸了 之类的东西(不好的命名无济于事:()。

emergtech 回答:从Symfony中的数据库中获取对象

您是否检查查询是否有效? 如果它在您的代码中有问题

首先让我们清理一些代码。

MainController.php

    public function showAction()
    {
        //todo: show domains for current user

        $currentUser = $this->getUser()->getID();
        $workspaces = $this->getDoctrine()
            ->getRepository(Domain::class)
            ->getDomainsByUser($currentUser);

        return $this->render('workspaces.html.twig',array('workspaces' => $workspaces));
    }

DomainRepository.php

public function getDomainsByUser($currentUser)
{
    return $this->createQueryBuilder('d')
        ->andWhere('d.users = :val')
        ->setParameter('val',$currentUser)
        ->orderBy('d.id','ASC')
        ->setMaxResults(15)
        ->getQuery()
        ->getResult();
}

workspaces.html.twig

The problem in the code is in the twig part.
{{ domain.domain }} not {{ workspaces.number }}

{% for domain in workspaces %}
    <div class="workspace card">
        <div class="card-body">
            <h4 class="card-title">{{ domain.domain }}</h4>
            <a href="/project" class="card-link">Card link</a>
        </div>
    </div>
{% endfor %}
,

由于您的Domain Entity似乎有一个名为domain的字段,因此命名似乎有点不对。因此,您的解决方案将如下所示:

{% for domain in workspaces %} //loop workspaces = every domain object
    <div class="workspace card">
        <div class="card-body">
            <h4 class="card-title">{{domain.domain}}</h4> //access domain field in object domain
            <a href="/project" class="card-link">Card link</a>
        </div>
    </div>
{% endfor %}

您遍历所有domain objects并访问要使用的字段domain

请告诉我这是否对您有所帮助,或者我是否误解了一些东西。

本文链接:https://www.f2er.com/3113872.html

大家都在问