0

I hope there are a few helpful and prefer German Symfony experts. For many years I have been working with PHP and now I tryed in a framework. I chose Symfony now because I like the components the most. The QueryBuilder and I stand on a war foot - I just do not understand it. Storing values works very well so far, though I doubt that I'm doing this in the sense of the framework. I'm really helpless. Currently I managing it by chasing everything in raw format but I'm not really happy with it.

How I can implement the following with Doctrine?

use App\Entity\Questions;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManager;

class QuestionsController extends AbstractController
{
/**
 * @Route("/addquestion", methods={"POST","HEAD"})
 */
public function addQuestion()
{
    $entityManager = $this->getDoctrine()->getManager();

    $RAW_QUERY = 'SELECT COUNT(*) AS c FROM questions WHERE questToID = '.$_POST['u'].' AND  questFrom = '.$this->getUser()->getId().';';


    $statement = $entityManager->getConnection()->prepare($RAW_QUERY);
    $statement->execute();

    $total = $statement->fetchAll();

    if($total[0]['c'] >= 3)
    {
        return new Response('error|Du kannst der selben Person maximal drei Fragen stellen.');  
    }
 [...]

I have already tried to implement this, and many other things (no avail): Count Rows in Doctrine QueryBuilder

Since I speak bad English, I very much hope that you understand me…

2 Answers2

0

One simple way of doing that would be something like this (with the assumption that you have a "Question" entity - and that the fields defined there are matching with the column names from your raw query).

$em = $this->getDoctrine()->getManager();
$userQuestions = $em->getRepository(Question:class)->findAll(['questToID' => $_POST['u'], 'questFrom ' => $this->getUser()->getId()]);

$total = count($userQuestion);

Or if you prefer to have just the count from the query instead of fetching all the matching objects and counting them, you can write the query builder part something like this (in this format this is meant to be written in your controller as you have with your raw query - in general the "correct" place would be QuestionRepository.php class from where this would be just called in controller):

$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder('q');
$qb->select('count(q)');
$qb->andWhere('q.questToID = :questToID');
$qb->andWhere('q.questFrom = :questFrom');

$qb->setParameter('questToID', $_POST['u']);
$qb->setParameter('questFrom ', $this->getUser()->getId());

$total = $qb->getQuery()->getSingleScalarResult();
ejuhjav
  • 2,660
  • 2
  • 21
  • 32
  • both seem somehow not to work. The last suggestion ends with: Uncaught PHP Exception Doctrine\ORM\Query\QueryException: "[Syntax Error] line 0, col 24: Error: Expected Doctrine\ORM\Query\Lexer::T_FROM, got 'WHERE'" at C:\xampp\htdocs... –  May 27 '19 at 11:05
  • Can you try with the updated version? In general, both answers work based on some assumption because your question doesn't contain all the necessary information for giving an exact answer. Namely how your Question entity class is defined for the related parts (class name, the two search fields). – ejuhjav May 27 '19 at 12:55
  • indeed, that works after I've added the @ORM \ Entity (repositoryClass = "App \ Repository \ RequestsRepository"). I'm really happy about that. :-) Many Thanks. It's almost like learning a new programming language –  May 27 '19 at 13:13
0

so getting the value with $_POST['u'] is not recommended her you can either pass the value with the route an retrieve it as a parameter for the function:

/**
 * @Route("/addquestion/{u}", methods={"POST","HEAD"})
 */
public function addQuestion($u)

or you can get it out from the request it self:

/**
 * @Route("/addquestion", methods={"POST","HEAD"})
 */
public function addQuestion(Request $request)

if you want to use the query builder the best practice would be to create a repository for you entity and make you the query there:

namespace App\Repository;

use App\Entity\Questions;
use Doctrine\ORM\EntityRepository;

class QuestionsRepository extends EntityRepository
{
    public function findUserQuestions($user, $u)
    {
          $queryBuilder = $this->createQueryBuilder('c')
            ->where('c.questToID = :questToID')
            ->andWhere('c.questFrom = :questFrom')
            ->setParameters(['questToID'=>$u,'questFrom'=>$user]);
            return $queryBuilder->getQuery()->getResult();
    } 

and in you controller you can get the result:

$userQuestions = $this->getDoctrine()->getRepository(Questions::class)->findUserQuestions($this->getUser(), $u);

count($userQuestions);

i hope this will be useful in your case and explain you a bit how its done in symfony

Ali Mhanna
  • 199
  • 2
  • 15
  • Thank you, but that does not work for me :( It ends with the error message: Undefined method 'findUserQuestions'. The method name must start with either findBy, findOneBy or countBy! I tried to rename it to findBy ... but then it says: Uncaught PHP Exception Doctrine \ ORM \ ORMException: "Entity 'App \ Entity \ Questions' has no field' userQuestions' You can not call 'findByUserQuestions' on the entities' repository" I can not handle the mistakes of Symfony :-( –  May 27 '19 at 11:21
  • you cant rename it to findBy because its already exist, and the error you getting is because it cant find the repository because of the use i just edited the answer try please to use App\Entity\Questions; and let me know if it did work , i updated the answer try now please – Ali Mhanna May 27 '19 at 11:31
  • okay, thanks, that works. In my entity class was missing: / ** * @ORM \ Entity (repositoryClass = "App \ Repository \ QuestionsRepository") * / class questions {...} But now I have a new error: Return value of App \ Repository \ QuestionsRepository :: findUserQuestions () must be returned to the type array, object returned It's really cursed Symfony and I probably do not fit together :-D –  May 27 '19 at 12:47
  • just take the :array after the repository function and try to dump the result to see what are you getting back from the function .... you do you just need some time to get used to Symfony ;) – Ali Mhanna May 27 '19 at 13:15
  • So far, despite all the difficulties I find Symfony totally great, but the ": array" to remove is unfortunately not enough. I had already tried that. –  May 27 '19 at 13:25
  • i am working with symfony for a while and its gets only more interesting ... it might be that we passed the user object instead of the user id $user->getId() inside the fnunction – Ali Mhanna May 27 '19 at 13:31
  • I noticed that before, but I can not get any result: $ userQuestion = $ this-> getDoctrine () -> getRepository (Questions :: class) -> findUserQuestions ($ this-> getUser () -> getId (), $ request-> request-> get ('u')) ; var_dump (count ($ user question)) die (); Warning: count (): parameter must be an array or object that implements countable –  May 27 '19 at 14:02
  • oh sorry my bad i totally forgot to the get result at the end of the Query :: $queryBuilder->getQuery()->getResult(); – Ali Mhanna May 27 '19 at 14:08
  • Has definitely led to a new mistake :-D [Semantic Error] line 0, col 45 near 'questToID =: questToID': Error: Class App \ Entity \ Questions has no field or association named questToID ... although that exists ... ` / ** * @var int * * @ORM \ Column (name = "questToID", type = "integer", nullable = false) * / private $ questtoid;` –  May 27 '19 at 14:19
  • there is a difference between the variable name and the defined name inside the orm (private $ questtoid) and (name = "questToID") and this is wrong you can take the name inside the orm out you dont need it just use it like this: /** * @var integer $questToID * * @ORM\Column(type="integer", nullable=true) */ private $questToID; – Ali Mhanna May 27 '19 at 14:40
  • it will be better to post the whole entity class to check it – Ali Mhanna May 27 '19 at 14:42
  • I have just done that. Unbelievable, I do not understand that. The table I had imported from an existing and generated. Now I created the table again and it works. :-D Thank you very much –  May 27 '19 at 14:47
  • my pleasure :). it might get some time a bit tricky good luck and have fun with symfony – Ali Mhanna May 27 '19 at 14:52
  • Thank you, I hope you stay here for a long time :) –  May 27 '19 at 14:56
  • I do work in Germany but i am not german.mein deutsch ist nicht genug solche Sachen zum erklären ;) – Ali Mhanna May 27 '19 at 18:19
  • That's funny, because my english is not good enough to understand symfony. You really helped me a lot. Thanks again :) –  May 28 '19 at 02:16