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

Fetching objects from database in Symfony

我有实体域,其中包含字段 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 %}

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();
}

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

我知道我不知何故搞砸了 for 之类的(糟糕的命名没有帮助 :( ).

命名似乎有点不对劲,因为您的 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

您是否检查过您的查询是否有效? 如果它正常工作,则说明您的代码有问题

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

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 %}