Symfony2 - how can I get Entity Object based on custom query? - mysql

this is my custome query:
$query = $em->createQuery("SELECT max(d.id) FROM MyBundle:DBTableEntity d ");
$max_incoming_id = $query->execute();
I want it to return the Entity Object, just like this one below:
$EntityObj = $resource->getRepository("MyBundle:DBTableEntity")->findAll();
Any idea how to do that?

Something like this should work
$EntityObjects = $resource->getRepository('MyBundle:DBTableEntity')
->createQuery()
->orderBy('id', 'DESC')
->getResult();
$EntityObject = array_pop($EntityObjects);

Try This
$query = sprintf("SELECT s FROM BundleName:EntityClass s where s.field1 = %d and s.field2=%d", $field1, $field2);
$em = $this->getDoctrine()->getEntityManager();
$queryObj = $em->createQuery($query);
$entities = $queryObj->execute();

With excute you receive a array of results (entities).
so you can do $entities = $query.excute();
return $entities[0]; //this is if you have one result;
array_pop($entities) will not work this gives a error in symfony 2.6

I think you will like this style:
$EntityObj = $resource->getRepository("MyBundle:DBTableEntity")
->findOneBy(array(), array('id' => 'DESC'));
:)

Related

Joomla Development Database Select Query Giving Not unique table/alias

I'm developing a Joomla 3 component and I'm trying to select data from database using the Joomla framework classes. I'm getting a error Not unique table/alias. What could be the reason ?.
Code Snippet...
$app = JFactory::getApplication();
$job_id = JRequest::getVar('Jobid', null);
try {
$db = JFactory::getDbo();
$query = $db->getQuery(true);//Here Was The Problem
$query->select(array('A.state AS approval_state', 'A.*', 'B.*', 'C.district_name', 'D.educational_qualification', 'E.current_job_status'))
->from($db->quoteName('#__pes_job_provider_request_cv_info') . 'AS A')
->join('LEFT', '#__pes_jobseeker_profile AS B ON B.jobseeker_profile_id = A.jobseeker_profile_id')
->join('LEFT', '#__pes_district AS C ON C.district_id = A.district_id')
->join('LEFT', '#__pes_highest_educational_qualification AS D ON D.highest_educational_qualification_id = B.highest_educational_qualification_id')
->join('LEFT', '#__pes_current_job_status AS E ON E.current_job_status_id = B.current_job_status_id')
->where($db->quoteName('A.job_order_registration_id') . ' = ' . $db->quote($job_id))
->order('B.name_in_full ASC');
$db->setQuery($query);
$results = $db->loadObjectList();
Thank You.
OK ! I figured out the reason.
The reason why this happened is that I haven't instantiated the query object as a new query.
i.e. $query = $db->getQuery();
So, in order to resolve the issue I simply gave the parameter boolean true for the query method
i.e. $query = $db->getQuery(true);

How to display a row count result in twig file

I am fetching a row count inside a repository and that query is returning an array as a result. How do i fetch the number count and display the result in my twig file?
This is the query fetching row count:
public function getTrailCount(){
$sql = "SELECT count(`id`) FROM `article` where `publish`='1' AND `catForFilter` like '%trail%' ";
$stmt = $this->connection->prepare($sql);
$stmt->execute();
$trailCount = $stmt->fetchAll(PDO::FETCH_ASSOC);
//$trailCount->getSingleScalarResult();
//echo '<pre>'; print_r($trailCount); exit;
return $trailCount;
}
In controller i am trying to fetch it like this, i know its a wrong procedure though:
foreach($trailCount as $trail){
$data['trailCount'] = $trail->count; //throughing an error
}
How to mend this code, any help is much appreciated. Thanks
In that case, using PDO::FETCH_NUM would be much simpler:
$trailCount = $stmt->fetchAll(PDO::FETCH_ASSOC);
...
foreach($trailCount as $trail){
$data['trailCount'] = $trail[0]; // Using "0" instead of named key
}
But if you still really want to use FETCH_ASSOC you would need:
$sql = "SELECT count(`id`) as cnt FROM `article ...... "
.....
foreach($trailCount as $trail){
$data['trailCount'] = $trail['cnt'];
}
Notice that I'm not using ->cnt but ['cnt'] since data returned from PDO is not object-based but array-bases instead.
Hope this helps a bit...
EDIT:
Given the lack of Twig part, I can only assume what you're trying to do:
/**
* #Route("/foo")
* #Template()
*/
public function fooAction(){
...
... The code above
...
return array('data' => $data);
}
And then, in your twig:
{{ data.trailCount }}
I got the solution with some help of Jovan Perovic, i did like this:
The query Part:
public function getTrailCount(){
$sql = "SELECT count(`id`) as cnt FROM `article` where `publish`='1' AND `catForFilter` like '%trail%' ";
$stmt = $this->connection->prepare($sql);
$stmt->execute();
$trailCount = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $trailCount[0]['cnt']; //instead of an array i passed the single value
}
in controller:
$trailCount = $clicknblog->getTrailCount();
return $this->render('AdventureBiddingBundle:Organiser:editProfileOrganiser.html.twig', array(
'trails' => $trailCount
));
in twig file i displayed the value directly:
<p>{{ trails }}</p>
Hope this helps to someone with same problem

Laravel 4.x, Eloquent multiple conditions

I've tried to this:
Product::where(['product_id' => $product->id, 'catalog_id' => $key])->first();
This isn't working at all. When I'm doing this:
Product:where('product_id', $product->id)->where('catalog_id', $key)->first();
It just works fine. I've searched in the documentation of Laravel,
and found nothing.
Is there any option to using the where function with an array in it ?
You need to use where() individually. If you want to dynamically building the query you can do something like:
$wheres = array('product_id' => $product->id, 'catalog_id' => $key);
$q = new Product;
foreach ( $wheres as $k => $v ) {
$q = $q->where($k, $v);
}
$products = $q->first();
In fact we were all wrong ;)
As of latest version of the framework you can do exactly what you wanted.
Check this commit and update Laravel if you need that feature.
https://github.com/laravel/framework/commit/87b267a232983abdac7c23c2dc6b1b270dd24b8a
Product::whereNested(function($query) use ($key, $product){
$query->where('product_id', $product->id);
$query->where('catalog_id', $key);
})->get();
Laravel's wheres use an and condition by default:
$products = Product::where('this','=','that')->where('something','=','hello')->get();
is somewhat equivalent to:
SELECT * FROM products WHERE this = 'that' AND something = 'hello';
You simply chain the ->where() methods together. No need for an array.
If you want to use an or condition:
$products = Product::where('this','=','that')->orWhere('something','=','hello')->get();

Doctrine Native SQL many-to-many query

I have a many-to-many relationship between Students and Programs with tables student, program, and student_program in my database.
I'm trying to join the two entities and perform some custom queries that require subqueries. This means that the Doctrine QueryBuilder cannot work because it does not support subqueries.
Instead, I'm trying the NativeSQL function and am making decent progress. However, when I try to SELECT something from the Program entity, I get the error Notice: Undefined index: Bundle\Entity\Program in vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php line 180.
$mapping = new \Doctrine\ORM\Query\ResultSetMappingBuilder($em);
$mapping->addRootEntityFromClassMetadata('Student', 's');
$mapping->addJoinedEntityFromClassMetadata('Program', 'p', 's', 'programs', array('id' => 'program_id'));
// Query based on form
$sql = 'SELECT s.id, s.last_name, p.name <---- problem when this is added
FROM student s
JOIN program p
';
$query = $em->createNativeQuery($sql, $mapping);
$students = $query->getResult();
Not a direct answer but doctrine 2 does indeed support sub queries. Just create a query then feed the dql into a where class. This example is somewhat verbose but it works just fine:
public function queryGames($search)
{
// Pull params
$ages = $this->getValues($search,'ages');
$genders = $this->getValues($search,'genders');
$regions = $this->getValues($search,'regions');
$sortBy = $this->getValues($search,'sortBy',1);
$date1 = $this->getValues($search,'date1');
$date2 = $this->getValues($search,'date2');
$time1 = $this->getValues($search,'time1');
$time2 = $this->getValues($search,'time2');
$projectId = $this->getValues($search,'projectId');
// Build query
$em = $this->getEntityManager();
$qbGameId = $em->createQueryBuilder(); // ### SUB QUERY ###
$qbGameId->addSelect('distinct gameGameId.id');
$qbGameId->from('ZaysoCoreBundle:Event','gameGameId');
$qbGameId->leftJoin('gameGameId.teams', 'gameTeamGameId');
$qbGameId->leftJoin('gameTeamGameId.team','teamGameId');
if ($projectId) $qbGameId->andWhere($qbGameId->expr()->in('gameGameId.projectId',$projectId));
if ($date1) $qbGameId->andWhere($qbGameId->expr()->gte('gameGameId.date',$date1));
if ($date2) $qbGameId->andWhere($qbGameId->expr()->lte('gameGameId.date',$date2));
if ($time1) $qbGameId->andWhere($qbGameId->expr()->gte('gameGameId.time',$time1));
if ($time2) $qbGameId->andWhere($qbGameId->expr()->lte('gameGameId.time',$time2));
if ($ages) $qbGameId->andWhere($qbGameId->expr()->in('teamGameId.age', $ages));
if ($genders) $qbGameId->andWhere($qbGameId->expr()->in('teamGameId.gender',$genders));
if ($regions)
{
// $regions[] = NULL;
// $qbGameId->andWhere($qbGameId->expr()->in('teamGameId.org', $regions));
$qbGameId->andWhere($qbGameId->expr()->orX(
$qbGameId->expr()->in('teamGameId.org',$regions),
$qbGameId->expr()->isNull('teamGameId.org')
));
}
//$gameIds = $qbGameId->getQuery()->getArrayResult();
//Debug::dump($gameIds);die();
//return $gameIds;
// Games
$qbGames = $em->createQueryBuilder();
$qbGames->addSelect('game');
$qbGames->addSelect('gameTeam');
$qbGames->addSelect('team');
$qbGames->addSelect('field');
$qbGames->addSelect('gamePerson');
$qbGames->addSelect('person');
$qbGames->from('ZaysoCoreBundle:Event','game');
$qbGames->leftJoin('game.teams', 'gameTeam');
$qbGames->leftJoin('game.persons', 'gamePerson');
$qbGames->leftJoin('game.field', 'field');
$qbGames->leftJoin('gameTeam.team', 'team');
$qbGames->leftJoin('gamePerson.person', 'person');
$qbGames->andWhere($qbGames->expr()->in('game.id',$qbGameId->getDQL())); // ### THE TRICK ###
switch($sortBy)
{
case 1:
$qbGames->addOrderBy('game.date');
$qbGames->addOrderBy('game.time');
$qbGames->addOrderBy('field.key1');
break;
case 2:
$qbGames->addOrderBy('game.date');
$qbGames->addOrderBy('field.key1');
$qbGames->addOrderBy('game.time');
break;
case 3:
$qbGames->addOrderBy('game.date');
$qbGames->addOrderBy('team.age');
$qbGames->addOrderBy('game.time');
$qbGames->addOrderBy('field.key1');
break;
}
// Always get an array even if no records found
$query = $qbGames->getQuery();
$items = $query->getResult();
return $items;
}

Doctrine LIMIT Syntax Error?

'[Syntax Error] line 0, col 71: Error: Expected end of string, got 'LIMIT''
Here's my code:
public function getLatestChapters()
{
return $this->_em->createQuery('SELECT c, m FROM models\Chapter c JOIN c.Manga m ORDER BY c.CreateDate LIMIT 10')->getResult();
}
What could posibly the problem for this? How can I use LIMIT in Doctrine?
I am using Doctrine 2
Seems like there is no LIMIT/OFFSET in DQL anymore.
$qb = $em->createQueryBuilder();
//.. build your query
$q = $qb->getQuery();
$q->setFirstResult($offset);
$q->setMaxResults($limit);
$result = $q->getResult();
I would Like to Contribute to this post and want to tell people that If you want to use DBAL with limit in your Unit Tests you can use following:
$client = static::createClient()
$em = $client->getContainer()->get('doctrine')->getManager();
$query = $em->createQuery('WRITE YOUR QUERY HERE');
$query->setFirstResult(0);
$query->setMaxResults(1);
$data = $query->getResult();
Same code can be used in controller also with some modifications :)