symfony中带有Php的数据表中foreach数据的重复结果

py49o6xq  于 2022-11-16  发布在  PHP
关注(0)|答案(1)|浏览(115)

我有一个用户列表和他执行的操作列表。当我试图显示用户已注册和两个表中的历史数据时,我得到了重复的结果。我使用HistoryManagerController来获取有关操作和执行这些操作的用户的信息。下面的代码可以正常工作,但我得到了重复的结果,其中表中的第一个结果匹配100%,第二个结果不匹配。然后继续为每个用户提供相同的重复值。我知道这些是人们需要做的基本事情,所以如果有人能为我指出正确的方向,我需要学习什么才能使这一切发生,这将帮助我贯穿我的项目。
谢谢你,谢谢你

历史控制器

<?php

namespace App\Controller;

use App\Entity\ActionHistorique;
use App\Entity\Users;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Services\HistoriqueLogs;
use Doctrine\Persistence\ManagerRegistry;


class GestionHistoriqueController extends AbstractController
{
    /**
     * @var HistoriqueLogs
     */
    private $logHistorique;
    /**
     * @var ManagerRegistry
     */
    private $doctrine;

    public function __construct(
        HistoriqueLogs $logHistorique,
        ManagerRegistry $doctrine
    ) {
        $this->logHistorique = $logHistorique;
        $this->doctrine = $doctrine;
    }
    /**
     * @Route("/gestion/historique", name="app_gestion_historique")
     */
    public function dashboardAdmin(RequestStack $requestStack): Response
    {
    $params = $requestStack->getSession();
    $user = $this->getUser();
    $projet =  $params->get('projet');
    $modules = $params->get('modules');
    $fonctionnalites = $params->get('fonctionnalites');
    $adresseWeb = $this->getParameter('adresse_web');

    $actionHistoriques = $this->doctrine->getRepository(ActionHistorique::class)->findBy(['projetId' => $projet->getId()]);

     $projetNom = $projet->getProjet();

    $dataJson = array();

foreach ($actionHistoriques as  $actionHistorique) {

    $listUsers = $this->doctrine->getRepository(Users::class)->findAll();

 /* getter pour récuperer les nom et prenom des id associé aux utilisateurs dans le tableau.
 Et ensuite faire le reste dans le deuxième foreach et call le tableau pour le remplir */

    foreach ($listUsers as $user) {
        
    $nomUser = $user->getNom();
    $prenomUser = $user->getPrenom();

        // Injection des données dans le tableau 
        $mesDonnes = array(

            "nom"=> $nomUser,
            "prenom"=> $prenomUser,
            "projet"=> $projetNom,
            "date"=> $actionHistorique->getDate()->format('d/m/Y'),
            "actionEffectuée"=> $actionHistorique->getAction(),
            "CodeST/TI/PT/LT/BP/BA"=> $actionHistorique->getCode(),
            "nomCode"=> $actionHistorique->getNom(),
        );
        
        $dataJson[] = $mesDonnes;          
    }
}
            return $this->render('Historique/gestionHistorique.html.twig', [
                'user' => $user,
                'projet' => $projet,
                'modules' => $modules,
                'fonctionnalites'=> $fonctionnalites,
                'adresseWeb'=> $adresseWeb,
                'actionHistorique'=> json_encode($dataJson),
            ]);
        }
    }

历史记录

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

{% block stylesheets %}
    {{ parent() }}
    {{encore_entry_link_tags('tabulator')}}

{% endblock %}
    {% block sudalysBody %}
    <section>
      <div id="singleTab" class="box box-info">
        <div class="box-header with-border">
    <h2 class="box-title">Historique Easy Exploit</h2>
        </div>
        <div id="infos">
<div>
  <select id="filter-field">
    <option value="nom">Nom</option>
    <option value="prénom">Prénom</option>
    <option value="projet">Projet</option>
    <option value="actionEffectuée">Action effectuée</option>
    <option value="CodeST/TI/PT/LT/BP/BA">Code de l'objet</option>
    <option value="nomCode">Nom de l'objet</option>
  </select>

  <select id="filter-type">
    <option id="filter-type" value="like"></option>
  </select>

  <input id="filter-value" type="text" placeholder="Rechercher">

  <button id="filter-clear">Réintialiser</button>
</div>
          <div id="monTable"></div>
        </div>
      </div>
    </section>
        
    {% endblock %}

{% block javascripts %}
    {{ parent() }}

<script>
 var gestionHistorique = '{{actionHistorique | e('js') | raw}}';
gestionHistorique = JSON.parse(gestionHistorique);

// gestionHistorique.forEach( e => {
//   console.log(e);
  
// });
  $(document).ready(function() {

//custom max min header filter
var minMaxFilterEditor = function(cell, onRendered, success, cancel, editorParams){

    var end;

    var container = document.createElement("span");

    //create and style inputs
    var start = document.createElement("input");
    start.setAttribute("type", "date");
    start.setAttribute("placeholder", "Min");
    start.style.padding = "6px";
    start.style.width = "50%";
    start.style.boxSizing = "border-box";

    start.value = cell.getValue();

    function buildValues(){
        success({
            start:start.value,
            end:end.value,
        });
    }

    function keypress(e){
        if(e.keyCode == 13){
            buildValues();
        }

        if(e.keyCode == 27){
            cancel();
        }
    }

    end = start.cloneNode();
    end.setAttribute("placeholder", "Max");

    start.addEventListener("change", buildValues);
    start.addEventListener("blur", buildValues);
    start.addEventListener("keydown", keypress);

    end.addEventListener("change", buildValues);
    end.addEventListener("blur", buildValues);
    end.addEventListener("keydown", keypress);

    container.appendChild(start);
    container.appendChild(end);

    return container;
 }

//custom max min filter function

function 
minMaxFilterFunction(headerValue,rowValue,rowData,filterParams) {
//headerValue - the value of the header filter element
//rowValue - the value of the column in this row
//rowData - the data for the row being filtered
//filterParams - params object passed to the headerFilterFuncParams property
//convert strings into dates

    if (headerValue.start != "") {
        headerValue.start = new Date(headerValue.start);
    }

    if (headerValue.end != "") {
        headerValue.end = new Date(headerValue.end);
    }

    if(rowValue){
        const [day, month, year] = rowValue.split('/');
        const result = [year, month, day].join('-');
        var rowValue1 = new Date(result);

        if(headerValue.start != ""){
            if(headerValue.end != ""){
                if(rowValue1 >= headerValue.start && rowValue1 <= headerValue.end){
                        return true;
                }else{
                    return false;
                }
            }else{
                if(rowValue1 >= headerValue.start){
                    return true;
                }else{
                    return false;
                }
            }
        }else{
            if(headerValue.end != ""){
                if(rowValue1 >= headerValue.end){
                    return true;
                }else{
                    return false;
                }
            }
        }
    }
    return true; 
//must return a boolean, true if it passes the filter.
}
//Define variables for input elements
var fieldEl = document.getElementById("filter-field");
var typeEl = document.getElementById("filter-type");
var valueEl = document.getElementById("filter-value");

//Trigger setFilter function with correct parameters
function updateFilter(){
  var filterVal = fieldEl.options[fieldEl.selectedIndex].value;
  var typeVal = typeEl.options[typeEl.selectedIndex].value;

  var filter = filterVal == "function" ? customFilter : filterVal;

  if(filterVal == "function" ){
    typeEl.disabled = true;
    valueEl.disabled = true;
  }else{
    typeEl.disabled = false;
    valueEl.disabled = false;
  }

  if(filterVal){
    table.setFilter(filter,typeVal, valueEl.value);
  }
}

//Update filters on value change
document.getElementById("filter-field").addEventListener("change", updateFilter);
document.getElementById("filter-type").addEventListener("change", updateFilter);
document.getElementById("filter-value").addEventListener("keyup", updateFilter);

//Clear filters on "Clear Filters" button click
document.getElementById("filter-clear").addEventListener("click", function(){
  valueEl.value = "";

  table.clearFilter();
});
var table = new Tabulator("#monTable", {
     
          data: gestionHistorique,
          layout: "fitColumns",
          pagination: "local",
          paginationSize: 20,
          paginationSizeSelector: [20, 40, 60, 100],
          paginationCounter: "rows",
          paginationCounter: "rows",
    columns:[
        {title:"Nom", field:"nom",hozAlign:"center"},
        {title:"Prénom", field:"prenom",hozAlign:"center"},
        {title:"Projet", field:"projet",hozAlign:"center"},
        {title:"Date", field:"date", sorter:"datetime",hozAlign:"center",formatter:"datetime", formatterParams:{
                inputFormat:"dd/MM/yyyy",
                outputFormat:"dd/MM/yyyy",
                invalidPlaceholder:"(invalid date)",
            },  headerFilter:minMaxFilterEditor, headerFilterFunc:minMaxFilterFunction, headerFilterLiveFilter:false},
         {title:"Action effectuée",field:"actionEffectuée",hozAlign:"center"},
        {title:"Code Objet", field:"CodeST/TI/PT/LT/BP/BA",hozAlign:"center"},
        {title:"Nom Objet", field:"nomCode",hozAlign:"center"},
    ],
    });
});

</script>
  
{% endblock %}
hmtdttj4

hmtdttj41#

1尝试移动代码:

$listUsers = $this->doctrine->getRepository(Users::class)->findAll();

在foreach之前:

...
$dataJson = array();

$listUsers = $this->doctrine->getRepository(Users::class)->findAll();

foreach ($actionHistoriques as  $actionHistorique) {

/* getter pour récuperer les nom et prenom des id associé aux utilisateurs dans le tableau.
   Et ensuite faire le reste dans le deuxième foreach et call le tableau pour le remplir */
...

我在迭代entityRepository find()调用时遇到过类似的问题。
如果它不能解决你的问题,至少你会有更好的表现。

编辑:
2在代码中,您似乎没有检查正在迭代的操作是否由内部foreach中的用户执行。因此,对于从数据库中检索到的每个操作和每个用户,您都要在**$mesDonnes**数组中添加一个条目。

我假设这两个表是通过外键或其他引用链接的,代码应该更像这样:

foreach ($actionHistoriques as $actionHistorique) {
   $user = $actionHistorique->getUser();
   $nomUser = $user->getNom();
   $prenomUser = $user->getPrenom();
   $mesDonnes = ....
           
   $dataJson[] = $mesDonnes;
}

//or
foreach ($actionHistoriques as $actionHistorique) {
   foreach ($listUsers as $user) {
       // madeThisAction() is a method that you should code specifically for your project
       if ($user->madeThisAction($actionHistorique)) {       
           $nomUser = $user->getNom();
           $prenomUser = $user->getPrenom();
           $mesDonnes = ....
           
           $dataJson[] = $mesDonnes;
       }
   }
}

相关问题