I am very new to coding, especially with Symfony. But now my teacher has given me a task to create a query to search within 2 attributes. I have started writing the query, but there is still a lot lacking. I am wondering if someone can help, or send a link to help me finish it.
I need to make a search option which looks up into Artikelnummer and Omschrijving.
/**
* #Route("/artikel/zoek", name="zoekartikel")
*/
Public function zoek(Request $request){
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT a
FROM AppBundle:Artikel a
WHERE a.artikelnummer = input AND a.omschrijving LIKE input2'
);
$artikelen = $query->getResult();
return new Response($this->render('search.html.twig',
array('artikelen' => $artikelen)));
}
You need first to instantiate Result Mapping
use Doctrine\ORM\Query\ResultSetMapping;
$rsm = new ResultSetMapping();
Then
$query = $em-> createNativeQuery(
'SELECT a
FROM AppBundle:Artikel a
WHERE a.artikelnummer = ? AND a.omschrijving LIKE ?',
$rsm
);
$query->setParameter(1, 'input1'); // or var
$query->setParameter(2, 'input2'); // or var
$artikelen = $query->getResult();
return new Response($this->render('search.html.twig',
array('artikelen' => $artikelen)));
More docs here http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html
Related
My normal query was looking like this.
$qb = $placeRepository->createQueryBuilder('p');
var_dump($qb->getQuery()->getResult());
I'll get few results as objects.
So this is the normal behaviour.
Then I want to add a custom field with ResultSetMapping.
$qb = $placeRepository->createQueryBuilder('p');
$qb->addSelect('123 as distance');
$rsm = new ResultSetMapping;
$rsm->addEntityResult(Place::class, 'p');
$rsm->addFieldResult('p', 'id', 'id');
$rsm->addScalarResult('distance', 'distance');
var_dump($qb->getQuery()->setResultSetMapping($rsm)->getResult());
With a ResultSetMappingBuilder its also not working.
$qb = $placeRepository->createQueryBuilder('p');
$qb->addSelect('123 as distance');
$rsm = $placeRepository->createResultSetMappingBuilder('p');
var_dump($qb->getQuery()->setResultSetMapping($rsm)->getResult());
Not working means: Array with zero items in it.
Ok found it.
But not working like I want 😢
/** #var \Doctrine\ORM\EntityManager $em */
$em = $this->getDoctrine()->getManager();
// Working but bad because defining all by yourself
$rsm = new ResultSetMapping();
$rsm->addEntityResult(Place::class, 'p');
$rsm->addFieldResult('p','p_id','id');
// Good
$rsmB = new ResultSetMappingBuilder($em);
$rsmB->addRootEntityFromClassMetadata(Place::class, 'p');
// Not working because separate field
//$rsmB->addScalarResult('distance', 'distance');
// Not working because not found ... (not a #ORM\Column)
$rsmB->addFieldResult('p', 'distance', 'distance');
I added comments why its not working.
Now I'm going to loop 😅
I am trying to get objects from DQL query.
Here is my code :
$em = $this->getDoctrine()->getRepository(Item::class);
$items = $em->createQuery($getQuery);
$items = $query->getResult();
$getQuery = DQL query string : SELECT from Entity WHERE ...
I am receiving error : Undefined method 'createQuery'. The method name must start with either findBy or findOneBy!
I don't understand it, bcz this example is copied from official documentation.
How I can execute DQL query in queryBuilder/createQuery?
Entity manager has a createQuery method.
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery($getQuery);
$items = $query->getResult();
Repository has a createQueryBuilder method.
$em = $this->getDoctrine()->getManager();
$qb = $em->getRepository(Item::class)->createQueryBuilder();
$query = qb->select('[columns]')->from('Entity')->where('[condition]')->getQuery();
$items = $query->getResult();
I building application in Symfony 2.
I have to filter users basing on data passed in form.
I wrote something like this in my controller:
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$qb->addSelect('user');
$qb->from('Application\Sonata\UserBundle\Entity\User', 'user');
if(($filter['freelancer'])){
$qb->setParameters(array('freelancer' => $filter['freelancer']))
->andWhere('user.firstname = :freelancer');
}
if(($filter['category'])){
$qb->innerJoin('Flexihub\MainBundle\Entity\Category', 'category', 'WITH', 'user.category = category.id')
->setParameters(array('category' => $filter['category']))
->andWhere('user.category = :category');
}
$query = $qb->getQuery();
$result = $query->getResult();
dump($result);
Im stuck with error when im trying to pass both parameters.
Invalid parameter number: number of bound variables does not match number of tokens
What am I doing wrong?
Is there better solution to solve my problem?
It's logical to write it like this, so, first add criteria then provide arguments:
if(($filter['freelancer'])){
$qb
->andWhere('user.firstname = :freelancer')
->setParameter('freelancer', $filter['freelancer']);
}
if(($filter['category'])){
$qb
->innerJoin('Flexihub\MainBundle\Entity\Category', 'category', 'WITH', 'user.category = category')
->andWhere('user.category = :category')
->setParameter('category', $filter['category']);
}
I am learning Yii2, when I do listing with custom query I am getting error:
The "query" property must be an instance of a class that implements the QueryInterface e.g. yii\db\Query or its subclasses.
I am getting data from query but when I put in dataprovider it is giving me error. Here is my code:
public function search($params) {
//$query = User::find();
$query = new \yii\db\Query;
$query = $query->select(['user.*','tbl_region.id','tbl_region.regionName'])
->from('user')
->join('LEFT JOIN','tbl_men_reg_info','tbl_men_reg_info.userID = user.id')
->join('LEFT JOIN','tbl_women_info','tbl_women_info.userID = user.id')
->join('LEFT JOIN','tbl_region','tbl_men_reg_info.region = tbl_region.id');
$command = $query->createCommand();
$query = $command->queryAll();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
return $dataProvider;
}
Can anyone please tell me how to do listing with custom query?
The error is kind of clear, you need to pass instance of yii\db\Query to data provider, so remove these lines:
$command = $query->createCommand();
$query = $command->queryAll();
and it should work.
Note that you also need to use SqlDataProvider instead of ActiveDataProvider, since models are not involved.
Also modifying variable with different type and meaning is considered bad practice:
$query = $command->queryAll();
It's not $query at this point, it's better to rename it for example as $rows or $results.
I want to get one single value from entity.Can anyone help me here.
Here is my code.Please let me know what is missing here.
$query = $em->createQuery("SELECT e FROM AdminBundle:MailTemplates e WHERE e.keyword = '" .$keywordVal."'");
$query->execute();
$result = $query->getResult();
echo $result ->getId();
Here i want the 'id'.
This is noted in the documentation how you can do this.
So given you're code this will become:
$query = $em->createQuery("SELECT e.id FROM AdminBundle:MailTemplates e WHERE e.keyword = ?1");
$query->setParameter(1, $keywordVal);
$query->execute();
$result = $query->getResult(); // array of MailTemplates ids
Note: I also made use of setParameters instead of setting the value directly in the query.
In your controller:
$this->get('database_connection')->fetchColumn('select id from mail_templates where...');
That's much better for performance and much easier if you don't want to have a deal with query builder and other doctrine orm stuff.
Using the query builder you could do...
$queryBuilder = $em->createQueryBuilder('e');
$queryBuilder
->select('e.yourColumn')
// This will return just this column
// Alternatively you could omit any select to return the whole object
// that you could then use like $object->getYourColumn() if you so chose
->where($queryBuilder->expr()->eq('e.keyword', ':keyword'))
->setParameter('keyword', $keyword)
;
return $queryBuilder
->getQuery()
->getResult();
try this on loading Entities instead of creating own queries
Loading the entity with the Repository.
$rep = $this->getDoctrine()->getManager()->getRepository("Bundlename:Entity");
//find one by keyword -> single entity
$entity = $rep->findOneBy(array('keyword' => $keyword));
//find all by keyword - Array of entities
$result = $rep->findBy(array('keyword' => $keyword));