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

Alv*_*vin 0 php doctrine for-loop symfony twig

我有实体Domain,它具有字段ID,域,字段用户中的用户,我有一个ID,它是创建该域的用户的ID。

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

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

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 %}
Run Code Online (Sandbox Code Playgroud)

MainController.php

{% 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 %}
Run Code Online (Sandbox Code Playgroud)

DomainRepository.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));
}
Run Code Online (Sandbox Code Playgroud)

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

我知道我有点搞砸什么(不好的命名没有帮助:()。

小智 5

您检查查询是否正常吗?如果它的工作在您的代码中有问题

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

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));
    }
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

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 %}
Run Code Online (Sandbox Code Playgroud)