mohasalim
mohasalim

Reputation: 47

Fetching Objects from the Database don't work in Symfony 4

i have a problem when i use the find() method in symfony :

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 't10.id' in 'on clause'

It's only with a specific Entity , with the others this is working perfectly.

Here my code :

$classeId = $_POST['classeid'];
                $repo = $this->getDoctrine()->getRepository(Classe::class);
                $classe = $repo->find($classeId);

and my entity :

 <?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\ClasseRepository")
 */
class Classe
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Formation", inversedBy="classe")
     */
    private $formation;

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Calendar", mappedBy="classe", cascade={"persist", "remove"})
     */
    private $calendar;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\person", inversedBy="classes")
     */
    private $responsable;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getFormation(): ?Formation
    {
        return $this->formation;
    }

    public function setFormation(?Formation $formation): self
    {
        $this->formation = $formation;

        return $this;
    }

    public function __toString() {
        return $this->name;
    }

    public function getCalendar(): ?Calendar
    {
        return $this->calendar;
    }

    public function setCalendar(?Calendar $calendar): self
    {
        $this->calendar = $calendar;

        // set (or unset) the owning side of the relation if necessary
        $newClasse = $calendar === null ? null : $this;
        if ($newClasse !== $calendar->getClasse()) {
            $calendar->setClasse($newClasse);
        }

        return $this;
    }

    public function getResponsable(): ?person
    {
        return $this->responsable;
    }

    public function setResponsable(?person $responsable): self
    {
        $this->responsable = $responsable;

        return $this;
    }
}

I searched the error but most post say its because the primary key is not id but in my case the primary key is id. I tried also to fetch object with the method findBy() and use other parameters than the id but i got the same error. My full code :

the class : http://www.pastebin.com/r7hREPYD , the repository : http://www.pastebin.com/Mp118dQt , the controller : http://www.pastebin.com/q29UnyGd

Upvotes: 0

Views: 1254

Answers (5)

mohasalim
mohasalim

Reputation: 47

The error come from bad associations with the entity. So i deleted the entity and all associations and re create the class and now its working.

Upvotes: 0

Preciel
Preciel

Reputation: 2827

The way you're working with Symfony 4 is wrong.
Using directly $_POST, $_SERVER, etc is not recommanded.

This is how your newcalendar function should be :

public function newcalendar(Request $request, JobRepository $jobRepository, ClasseRepository $classeRepository) {
    $user=$this->getUser();
    if($user) {
        $currentStep=$user->getStep();

        // Custom query result could be optimised
        $jobId=$this->getJobId($user->getId())[0]['job_id'];

        // Use Job repository instead
        // $repo = $this->getDoctrine()->getRepository(Job::class);
        $job=$jobRepository->find($jobId);

        //Do not override your object, create a new varaible instead, or use getter directly
        // $job=$job->getName();
        if($currentStep < 10) {
            return $this->redirectToRoute("registration$currentStep");
        }
        if($job->getName() == 1 || $job->getName() == 'admin' || $job->getName() == "responsable de formation" || $job->getName() == "consseiller") {

            // Do not use $_SERVER directly, may cause issues with fragments
            // if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if($request->isMethod('POST')) {

                // Same reason as $_SERVER
                $calendar=new Calendar();
                // $calendar->setStartDate($_POST['start']);
                $calendar->setStartDate($request->request->get('start'));
                // $calendar->setEndDate($_POST['end']);
                $calendar->setEndDate($request->request->get('end'));
                // $calendar->setEvent($_POST['event']);
                $calendar->setEvent($request->request->get('event'));
                // $classeId=$_POST['classeid'];
                $classeId=$request->request->get('classeid'); // Not used

                // Uncomment to check this value
                // dump($request->request->get('classeid'));
                // exit();

                // Use Classe repository instead
                // $repo=$this->getDoctrine()->getRepository(Classe::class);
                // $classe=$repo->find($request->request->get('classeid'));
                $classe=$classeRepository->find($request->request->get('classeid'));

                //check if not null
                if($classe) {
                    $calendar->setClasse($classe);
                    $em=$this->getDoctrine()->getManager();
                    $em->persist($calendar);
                    $em->flush();
                }

                return $this->redirectToRoute('calendar');
            }

            return $this->render("formation/newcalendar.html.twig");
        } else {
            return $this->render("dashboard/index.html.twig", array(
                'controller_name'=>'DashboardController',
            ));
        }
    }

    // Could be handled by firewall
    return $this->redirectToRoute('security_login');
}

I left a few comments in the code.

Regarding the last line of this function, forcing login could be handle by Symfony firewall in config/packages/security.yaml

Symfony Security
Symfony access control

Please correct your code first. You will notice that I left a dump in your code, uncomment it, and check that classeid is a valid value.

Looking at the Exception log, it's most likely the reason of your error

[EDIT] Just to make sure, please run the following commands:

php bin/console make:migration
php bin/console doctrine:migrations:migrate

Upvotes: 1

Imanali Mamadiev
Imanali Mamadiev

Reputation: 2654

Try find with namespace:

$classeId = $_POST['classeid'] ?? 1;

OR

$classeId = $request->request->get('classeid', 1); //By default your id = 1

$this->getDoctrine()->getRepository(App\Entity\Classe::class)->find($classeId);

And have you update your database:

doctrine:schema:update

after this try again.

Upvotes: 1

snipershady
snipershady

Reputation: 307

please try to write a repository function. Just to understand the problem.

public function findThisDamnId(int $id): array    {

    $qb = $this->createQueryBuilder('c')
        ->where('c.id > :val')
        ->setParameter('val',  $id)            
        ->getQuery();

    return $qb->execute();
}

or try the SQL standard

public function getThisDamnClassFromId(int $Id): array {
$conn = $this->getEntityManager()->getConnection();

$sql = '
    SELECT * FROM classe c
    WHERE c.id > :val';
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $id]);


return $stmt->fetchAll();
}

Upvotes: 0

snipershady
snipershady

Reputation: 307

first of all, you hadn't to use $_POST directly, but you have to use Request like that.

public function foo(Request $request): void {
   $classId = $request->request->get('classId');
   $classe = $this->getDoctrine()
        ->getRepository(Product::class)
        ->find($classId);

   ...
}

Maybe your unsanitized id is the problem.

You can try to write a method with the repo of the class as a formal parameter.

public function foo(Request $request, ClasseRepository $repoClass): void {
      $repoClass->find($request->request->get('classId'));
      ...
}

I would like to suggest you, to force the "classId" with one hardcoded.

$repoClass->find(1); // where 1 is a db you watched from db directly.

or

$repoCLass->findOneBy(['id'=> 1]); // where 1 is a well known unique identifier.

Upvotes: 1

Related Questions