I am developing an application using Symfony2 and DQL for building some queries in the repositories. I have the next code in the controller:
$emGalPak = $this->getDoctrine()->getEntityManager();
$OsatugabeKop = $emGalPak->getRepository('AnotatzaileaAnotatzaileaBundle:GalderaPaketea')
->getOsatugabeKop();
and this is the query I built in the repository corresponding to the entity mentioned above:
<?php
namespace Anotatzailea\AnotatzaileaBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* GalderaPaketeaRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class GalderaPaketeaRepository extends EntityRepository
{
public function getOsatugabeKop()
{
$qb = $this->createQueryBuilder('c')
->select('c')
->where('c.Osatua = 0')
$Emaitza = $qb->getQuery()->getResult();
return sizeof($Emaitza);
}
}
When running the code it shows the next error:
Parse error: syntax error, unexpected T_VARIABLE in /var/www/Symfony/src/Anotatzailea/AnotatzaileaBundle/Repository/GalderaPaketeaRepository.php on line 20
Any idea on how I can solve this error?
This has nothing to do with your query not working.
When you see a "Parse error" that means your PHP code itself is improperly formatted and the PHP engine cannot even parse it, let alone run it.
In this particular case, you're missing a semicolon at the end of your expression creating the query builder.
public function getOsatugabeKop()
{
$qb = $this->createQueryBuilder('c')
->select('c')
->where('c.Osatua = 0'); // <--- right there
$Emaitza = $qb->getQuery()->getResult();
return sizeof($Emaitza);
}
When you get the unexpected T_VARIABLE error that's almost always because you omitted a semicolon and the parser encountered a variable before it thought it should. It's easier to see the mistake if you take out the whitespace.
// Bad Code, two lines
$now = time()
$one = 1;
// Bad Code, one line
$now = time()$one = 1;
// ----------^ Pretty obvious now that a semicolon is missing
// And that a variable was encountered unexpectedly
Cheers
Semicolon missing after where line.
Related
I am following a tutoral on Symfony 4 where we want to create a raw query. Here is the code that is provided in the tutorial :
public function index(Request $request)
{
$entityManager = $this->getDoctrine()->getManager();
$conn = $entityManager->getConnection();
$sql = '
SELECT * FROM user u
WHERE u.id > :id
';
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => 3]);
//more code
}
But when I try to do the same the methode getconnection seem to not be recognized by my IDE and it gives me this message :
methode getconnection not found in \Doctrine\Common\Persistence\ObjectManager
Any ideas about what shoould I do ? I will apreciate it.
since it's not really an error, but more of a static analysis result, you can try to quiet the static analysis tool used (not exactly sure, which one it is) you could do this when getting your entity manager:
/** #var \Doctrine\ORM\EntityManagerInterface $entityManager */
$entityManager = $this->getDoctrine()->getManager();
if the static analysis tool is any good, it will accept the comment/hint and recognize the entity manager for what it truly is and probably will stop complaining.
(the question I ask myself: is there a reason you use plain SQL instead of ... you know ... the entity manager, like ... $user = $entityManager->find(User::class, 3); ... unless your User is not an entity for whatever reason)
I am trying to do a query in Symfony 3 to select the Commentaries of a Wish (Object Wishcom) with the contributionType included (Object ContributionType) thanks to a JOIN.
When running the webpage I get a:
Error: Method Doctrine\ORM\Query\Expr\Func::__toString() must not throw an >exception, caught Symfony\Component\Debug\Exception\ContextErrorException: >Catchable Fatal Error: Object of class DateTime could not be converted to >string
In the forums I could get that the datetime has to be converted with format. The thing is that I am not manipulating directly the date with my query although I know there is one DateTime attribute in my Wishcom object.
Should I select specifically the date and format it ? In that case were should it be done ? Or does the error come from something else ?
It seems the error comes from the where statement and the function ToString from Expr not being able to convert the date. I don't know what I should do.
$queryBuilder->where($queryBuilder->expr()->in('w.wish', $wish));
Here is my call in the controller:
$arraywishcom=$em->getRepository(Wishcom::class)->getWishcomWithContributionType($wish);
And my repository:
<?php
namespace Shaker\JRQBundle\Repository;
use Shaker\JRQBundle\Entity\Wish;
/**
* WishcomRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class WishcomRepository extends \Doctrine\ORM\EntityRepository
{
public function getWishcomWithContributionType(Wish $wish) {
$queryBuilder = $this
->createQueryBuilder('w')
->leftJoin('w.contributiontype', 'contributiontype')
->addSelect('contributiontype')
;
$queryBuilder->where($queryBuilder->expr()->in('w.wish', $wish));
return $queryBuilder
->getQuery()
->getResult()
;
}
}
I have found a different way of doing the query and it works.
Instead of the where I had with expr(), which was the problem, I did the following:
$queryBuilder->where('w.wish = :wish')->setParameter('wish', $wish);
But I still do not know why I got the error in the first place.
I am very new to Solr and I am probably missing something simple however, having followed Xavier Briand's presentation I have set up Symfony2, Solarium and Nelmio\SolariumBundle.
"nelmio/solarium-bundle": "2.0.*#dev",
"solarium/solarium": "3.0.*"
Having implemented a toSolrDocument method for my doctrine php object.
public function toSolrDocument(\Solarium_Document_ReadWrite $doc)
{
$doc->id = $this->getId();
$doc->description = $this->getTitle();
$doc->path = "path";
return $doc;
}
I am faced with the following error.
Catchable Fatal Error: Argument 1 passed to ::toSolrDocument() must be an instance of Solarium_Document_ReadWrite, instance of Solarium\QueryType\Update\Query\Document given, called in Controller.php
The controller calling this toSolrDocument method has the following function
public function indexItems(){
$client = $this->get('solarium.client');
// get an update query instance
$update = $client->createUpdate();
// create documents
$documents = array();
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('<Bundle>:<Object>');
$items = $repo->findAll();
foreach ($items as $item) {
$documents[] = $item->toSolrDocument($update->createDocument());
}
// add the documents and a commit command to the update query
$update->addDocuments($documents);
$update->addCommit();
// this executes the query and returns the result
$result = $client->update($update);
}
Most of this method again comes directly from Xavier's presentation and it is clear to see that the method $update->createDocument() does not return the correct type. In fact it returns an instance of the my php object. Does anyone know where I am going wrong here? Another thing that might be of help is that even when I try to pass a Solarium Document directly I get an exception.
foreach ($items as $item) {
$rw_item = new \Solarium_Document_ReadWrite();
$documents[] = $item->toSolrDocument($rw_item);
}
The exception is
FatalErrorException: Error: Class 'Solarium_Document_ReadWrite' not found in
I can't seem to find this class in any of the bundles and I am wondering if my setup might be causing the issues. Any help would be very much appreciated.
One additional point to note is that when I am running the solr jar I see the query requests come in from my symfony2 page it is only this indexing action that I can not work out so the config may be alright and I am miss understanding the use of the bundle.
You just need to use the correct class for the argument.
use Solarium\QueryType\Select\Result\AbstractDocument;
...
public function toSolrDocument(AbstractDocument $doc)
{
You could also not type hint it:
public function toSolrDocument($doc)
{
I am looking to run a custom query inside my entity class. I dont want to use table mapping for this query I just want to return an array of results but I would like the query to still log to the logger. I have stripped down the class and renamed to try and illustrate what I'm trying to achieve
// src/Name/ExampleBundle/Entity/ExampleEntity.php
namespace Name\ExampleBundle\Entity;
class ExampleEntity
{
public function getArrayFromExample(){
$results = $this->getEntityManager()
->createQuery("SELECT * FROM exmapleTable LIMIT 50")
->getResult();
return $results;
}
}
The above returns something like
Fatal error: Call to undefined method {path}\ExampleEntity::getEntityManager()
Your queries should be in an entity repository instead of the entity itself. http://mackstar.com/blog/2010/10/04/using-repositories-doctrine-2
Then you could do something like:
public function getArrayFromExample(){
$results = $this->_em
->createQuery("SELECT * FROM exmapleTable LIMIT 50")
->getResult();
return $results;
}
I am developing an application in symfony2 and using doctrine2. I created a custom repository class that has one function:
<?php
namespace Anotatzailea\AnotatzaileaBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* InterpretatzeaRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class InterpretatzeaRepository extends EntityRepository
{
public function getInterpDesberdinak($value)
{
$qb = $this->createQueryBuilder('c')
->select('DISTINCT c.attribute')
->where('c.fer = :Value')
->setParameter('Value', $value);
$Emaitza = $qb->getQuery()->getResult();
return $Emaitza;
}
}
What I want to get with this function is an array of all the "Interpretatzea" objects that have a distinct c.attribute and all have c.fer = value. Is the query correct? I would also want to know how to pass the value parameter to the repository function. Thanks
A cursory look at your repository method suggests it looks okay :) IIRC, I think the use of DISTINCT there is fine. If you do have problems you can always do a GROUP BY instead.
As for calling the repo method in a controller and passing a $value variable to it, that's pretty straightforward; for example:
// in your controller
$value = 'foo';
// get doctrine connection from DI, etc.
$em = $this->getDoctrine()
->getEntityManager();
// get the repository object for your
// entity and call your repository method
$result = $em->getRepository('AnotatzaileaAnotatzaileaBundle:Interpretatzea')
->getInterpDesberdinak($value);
// ... do something with your $result here
Note you use a concatenated version of your namespace and bundle, followed by a colon and the entity; e.g: AcmeTestBundle:User
Hope this helps :)