如何在symfony中显示数组关系ManyToMany

时间:2019-02-03 22:01:08

标签: php symfony

我正在学习symfony并制作一个项目。 我有两个实体User和Relation,它们之间的关系为ManyToMany。

所以我有一个具有用户ID和关系ID的表关系用户

我在MainController.php中有这个

 public function index(UserRepository $users,RelationRepository $relation)
{
    $user= $users->findAll();
    $relations =  $this->getDoctrine()->getRepository(Relation::class) ->findBy([],['id' => 'ASC']);
    return $this->render('main/index.html.twig', [
        'user' => $user,
        'relations'=>$relations
    ]);
}
public function family(UserRepository $users, RelationRepository $relation, $id)
{
     $user = $users -> findAll();
    $entityManager = $this->getDoctrine()->getManager();
        $relation = $entityManager->getRepository(Relation::class)->find($id);

    if($relation == null and $user ==null){
        return $this->redirectToRoute('main');
    }else{
    return $this->render('main/family.html.twig', [
        'relations' => $relation,
        'users' => $user,
    ]);
    }
}

我在index.html.twig中有这段代码

{% extends 'base.html.twig' %}

{% block title %}Family{% endblock %}

{% block body %}

<h1>Family</h1>
    {% for relation in relations %}
{% for users in user %}

<li><a href="{{ path('family',{'id':users.id}) }}">{{ users.firstname}} {{ users.partner }}</a></li>
{% endfor %}
{% endfor %}
{% endblock %}

谁显示2行: user_id_1(与关系_id_1)和user_id_1(与关系_id_2)

我想知道如何创建一个包含user_id_1且都具有Relation_id的数组

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您无需获取控制器中的所有关系即可。您的用户实体应实现getRelations()方法,该方法可让您执行以下操作:

{% for user in users %}
    User id {{ user.id }} is in relation with:
    <br>

    {% for relation in user.relations %}
        {# here you are looping through all relations of a user so you can use both user.id and relation.id and others fields related to relation entity #}

        - {{ relation.id }}<br>
    {% endfor %}
{% endfor %}

因此您可以在控制器中跳过$ relations查询:

// Not needed anymore:
$relations =  $this->getDoctrine()->getRepository(Relation::class) ->findBy([],['id' => 'ASC']);