Twig / PHP显示作者的数据 - 2个表(Symfony2)

时间:2015-03-26 18:48:55

标签: php symfony doctrine twig

我对Symfony来说比较新,并且有一个我无法解决的问题。

树枝视图中的for用于"查询"实体,试图通过"帖子"实体通过查询控制器来查看。希望这是有道理的。

控制器:

public function viewEnquireAction($id )
{
    $em = $this->getDoctrine()->getManager();
    $enquire = $em->getRepository('Bundle:Enquire')->find($id);

    $project = new Post();
    $author = $project->getAuthor(); //mutator from Post entity

    return $this->render('Bundle:Page:staff.html.twig', ['enquire' => $enquire, 'author' => $author]);
}

嫩枝:

{% for project in enquire %}
    {% if app.user == author.username %} //issue here.
        //return data will go here
    {% endif %}
{% endfor %}

本质上,我只是在登录作者的用户时尝试显示数据库中的数据。

感谢。

3 个答案:

答案 0 :(得分:1)

循环查询项目的代码@davidvelilla更加敏感,并检查项目作者是否与登录用户相同,只显示已连接用户的项目,您可以做的其他事情是使用存储库或项目与用户或用户之间的关系以及制作sens的作者。然后使用存储库中的函数通过user_id获取项目,您不必遍历所有项目,这是不好的做法并占用资源。

例如,您在数据库中有1000个项目,您有一个项目的用户。为什么从数据库1000项目加载并循环它们来检查user == author,同时你可以执行$repository->getProjectsById($user->getId()); //只加载所需的$项目(1)而不需要twig check。只显示数据。

答案 1 :(得分:0)

您的变量$ project刚刚实例化,除了您在Post.php中定义的默认值之外,不会包含有关$ author的信息

如果您的$ inquire实体具有正确的映射信息,则只将该变量传递给模板,并且我认为您正在尝试获取该查询的所有项目的作者。这样的事情可能会给你一个线索:

public function viewEnquireAction($id )
{
    $em = $this->getDoctrine()->getManager();
    $enquire = $em->getRepository('Bundle:Enquire')->find($id);

    return $this->render('Bundle:Page:staff.html.twig', ['enquire' => $enquire]);
}

{% for project in enquire.projects %}
    {% if app.user == project.author.username %} //issue here.
        //return data will go here
    {% endif %}
{% endfor %}

答案 2 :(得分:0)

一种更普遍的尝试,可以让您在应用中的任何地方重复使用“作者被允许查看”代码正在使用选民http://symfony.com/doc/current/cookbook/security/voters_data_permission.html

您可以保留现有的循环,但不是直接比较用户,而是可以使用以下内容:

{% if is_granted("LIST", project) %}
  <a href="{{ path('project_edit', { 'id': project.id }) }}">show project</a>
{% endif %}

如上所述,一个优点是你也可以在其他任何地方使用它,例如在控制器内:

public function editAction(Project $project)
{
    if (!$this->get('security.context')->isGranted('LIST', $project)) {
        // Throw access denied exception
    }
    // ...
}

除了“用户是作者”检查之外,您还可以添加其他规则。 也许你希望有ROLE_SUPER_ADMIN的用户总能看到一切。 只需将此添加到您的选民班级。