Manually writing DQL - php

I am trying this part in the Doctrine Documentation wherein you can:
Manually writing DQL
For you SQL buffs, we didn't forget about you. You can optionally write your DQL queries manually and parse them in to a Doctrine_Query instance or just execute them.
$dql = "FROM User u, u.Phonenumbers p";
$q = Doctrine_Query::create()->parseQuery($dql);
Or you can just execute them by using the query() method of Doctrine_Query.
$dql = "FROM User u, u.Phonenumbers p";
$q = Doctrine_Query::create()->query($dql);
Yet I'm having difficulties since I've encountered the following error:
Attempted to load class "Doctrine_Query" from namespace "AppBundle\Controller".
Did you forget a "use" statement for another namespace?
Could you please help me with this?
<?php
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Entity\TblProduct;
class DefaultController extends Controller
{
/**
* #Route("/", name="homepage")
*/
public function indexAction()
{
$products = "SELECT * FROM TblProduct";
$q = Doctrine_Query::create()->query($products);
if (!$products) {
throw $this->createNotFoundException(
'No products registered yet.'
);
}
return $this->render('default/index.html.twig', array('products' => $products));
}

This is part of Doctrine 1.2 and not Doctrine 2.5. In the latest version you would just create queries in the Doctrine Query Language with createQuery().
<?php
$dql = "FROM User u, u.Phonenumbers p";
$query = $em->createQuery($dql);
$users = $query->getResult();
Alternatively you can write Native SQL.

Related

Understanding problem Doctrine 2 ORM Query Builder in Symfony 4

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…
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
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();

How to integrate search by tag functionality into the wordpress with eloquent?

I have integrated wp-eloquent with wordpress and I would like to create a relation between tags and posts.
Normally wordpress built-in functions are using this type of queries which is pretty good:
SELECT *
FROM 0UU60c51_term_relationships
JOIN 0UU60c51_term_taxonomy
ON 0UU60c51_term_relationships.term_taxonomy_id = 0UU60c51_term_taxonomy.term_taxonomy_id
JOIN 0UU60c51_terms
ON 0UU60c51_terms.term_id = 0UU60c51_term_taxonomy.term_id
WHERE object_id = '13944' AND taxonomy = 'post_tag';
I am using this relations and this methods:
namespace WeDevs\ORM\WP;
use WeDevs\ORM\Eloquent\Model;
/**
* Class Post
*
* #package WeDevs\ORM\WP
*/
class Post extends Model
{
public function tags(){
return $this->terms("post_tag");
}
public function terms($term_type)
{
$closure = (function($query) use ($term_type) {
$query = $query->where("taxonomy",$term_type);
return $query;
});
return $this->belongsToMany('WeDevs\ORM\WP\Term','0UU60c51_term_relationships','object_id','term_taxonomy_id')->whereHas("term_taxonomy", $closure);
}
Actually results are the same for both :
print_pre(Post::find(13944)->tags->lists("name"));
But unless I didn't use lists method it brings a lot of queries, objects and results with the eloquent object. Is there a way to not getting relations and only getting tags without anything else ?

PHP: Symfony2 MySQL SELECT query in controler

I created a database on phpMyAdmin localhost. I have set database configurations in symfony and created doctrine mapper (entity). Now all I need is to make SELECT query and get information from database:
TABLE NAME: Profile
ROWS: 1
CONTROLLER CODE:
...
use Ignas\IgnasBundle\Entity\Profilis;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends Controller
{
public function indexAction()
{
$profilis = new Profilis();
return new Response('Id '.$profilis->getId());
}
}
getId method is from Entity/Profilis file Profilis class.
Is there any easy way to do this? I searched for a while and all I could find was doctrine syntax that is not familliar to me at all.
you can do it in different ways:
first of all, get the EntityManager in your Controller
$em = $this->getDoctrine()->getEntityManager();
in case it says it's deprecated you can also get it like:
$em = $this->getDoctrine()->getManager();
then you can do it with the QueryBuilder or with the createQuery method
With Select method (as suggested in the comments)
$profilis= $em->select('p.id')
->from('BundleName:EntityName', 'p')
->getQuery()
->getResult();
simple Query:
$query = $em->createQuery("SELECT * FROM Profilis p");
$profilis = $query->getResult();
NOTE
both methods return an array of Profilis so you can simply loop them this way:
foreach($profilis as $p){
// do whatever you want
}

Performing a custom query inside Doctrine entity

I have an entity (B) which is responsible for managing custom templates. Upon updating entity A I need to query entity B to fetch the desired template and do the necessary processing.
Something like:
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\EntityRepository;
use Bundle\EmailsBundle\Entity\Email;
use Symfony\Component\Validator\ExecutionContextInterface;
class MemberApplication extends EntityRepository
{
public function sendUpdateNotificationEmails()
{
// Send email to user
$emailRow = $this->getEntityManager()
->createQuery("SELECT * FROM emails where `type` = 'x' LIMIT 1")
->getResult();
}
(...)
}
This returns me an error:
Fatal error: Call to a member function createQuery() on a non-object in Classpath/Classname.php
Both $this->getEntityManager() and $this->_em is NULL.
I read a similar approach in http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes and I'm unable to figure out why this isn't working.
Thanks
this->getEntityManager() returns null because the dependence on doctrine is not injected. Try $this->getDoctrine()->getEntityManager(); instead. This should be done in the controller side though so something like this:
$em = $this->getDoctrine()->getManager();
$memberRepo = $em->getRepository('MyBundle:MemberApplication');
$result = $memberRepo->sendUpdateNotificationEmails();
then in your function you should return $emailRow or what you want.

Index hinting in Doctrine2

Is there a way to hint the use of an index in Doctrine2? The equivalent of the MySQL USE INDEX syntax:
SELECT * FROM user u USE INDEX(my_super_index) ...
I found a gist with working code using a custom tree walker: https://gist.github.com/arnaud-lb/2704404
Thanks to the author!
It will not work for RDBMS using a different syntax than MySQL though.
Update: The previous code does not work for queries with multiple tables in the FROM clause. So here is my updated version of the previous walker:
<?php
namespace __YOUR_NAMESPACE_;
use Doctrine\ORM\Query\SqlWalker;
class UseIndexWalker extends SqlWalker
{
const HINT_USE_INDEX = 'UseIndexWalker.UseIndex';
public function walkFromClause($fromClause)
{
$sql = parent::walkFromClause($fromClause);
$index = $this->getQuery()->getHint(self::HINT_USE_INDEX);
return preg_replace('/( INNER JOIN| LEFT JOIN|$)/', sprintf(' USE INDEX(%s)\1', $index), $sql, 1);
}
}
Notice that when you implements this on a Query in a repository in Symfony, you have to set FDQN for the value of the Hint Query::HINT_CUSTOM_OUTPUT_WALKER
<?php
namespace __YOUR_NAMESPACE_\Repository;
use Doctrine\ORM\Query;
use __YOUR_NAMESPACE_\UseIndexWalker;
class MyEntityRepository extends EntityRepository
{
public function myFunction()
{
$query = $this->entityManager->createQueryBuilder()->select('my_field')->from('my_entity', 'my_entity')->getQuery();
$query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, UseIndexWalker::class);
$query->setHint(UseIndexWalker::HINT_USE_INDEX, 'my_super_index');
}
}

Categories