Doctrine2 querystring query - php

Currently i develop an rest-api-app with symfony2 and doctrine2. My API should has the functionality to filter the results by an querystring.
For example, the following url:
http://example.com/api/users?orderBy=username%20DESC&limit=20
I can parse the querystring with parse_str($this->getRequest()->getQueryString(), $queryString); to an assoc array.
Is there any function that i can commit the array and doctrine selects the corresponding results? Something like $users = $this->getDoctrine()->getRepository('UserBundle:User')->findByQueryString($queryString);

As AdrienBrault said don't use parse_str instead put this in your controller:
$orderBy = $this->get('request')->query->get('orderBy');
$limit = $this->get('request')->query->get('limit');
$rep = $this->getDoctrine()->getRepository('UserBundle:User');
$users = $rep->findLimitOrderBy($orderBy, $limit);
And inside your user repository class:
public function findLimitOrderBy($orderBy, $limit)
{
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM UserBundle:User u
ORDER BY u.'.$orderBy
)
->setMaxResults($limit);
return $query->getResult();
}

You shouldn't use parse_str to access the query string parameters.
You can access the ParametersBag with $request->query. You could get an array with $request->query->all().
You can use the findBy method of the repository, that accepts an array with the following format:
array(
'field' => 'value',
'field2' => 'value2',
)
So you could do
$users = $userRepository->findBy($request->query->all());
But it won't support the orderBy parameter.

Related

symfony doctrine order by

I'm trying to use doctrine and take the values ordered, but I cannot.
I try so:
$articlesB = $this
->getDoctrine()
->getManager()
->getRepository('theBundle:Article')
->findAll(array('date' => 'ASC'));
Do you know howw to take this values ordered by date? A column is named date and take all the dates. I want to have this orderer.
Thanks
Best regards
Use findBy instead of findAll with an empty array for the first argument (selection criteria) and your sorting array as the second argument.
$articlesB = $this
->getDoctrine()
->getManager()
->getRepository('theBundle:Article')
->findBy(array(),array('date' => 'ASC'));
In this case I looked at the actual source code. You would think that findAll() would work but nope. It never passes the sorting criteria on.
You'll need to create an ArticleRepostory and in it:
public function getOrderedArticles()
{
$return $this->getEntityManager()
->createQuery(
"SELECT a FROM theBundle:Article a "
. "ORDER BY a.date ASC"
);
}
so that your controller could do
$articlesB = $this
->getDoctrine()
->getManager()
->getRepository('theBundle:Article')
->getOrderedArticles();

Using array as a condition in where clause codeigniter

I have the problems using the array input as a value in WHERE clause.
But don't want to use more than once in WHERE clause code.
In my case, this is what I want :
$cond = array('job_id' => $job_id_var, 'job_name' => $job_name_var);
//WHERE clause
$this->where($cond); //only using once WHERE clause code like this, array as input
//which means
WHERE job_id = '$job_id_var' AND job_name = '$job_name_var'
is it possible to do that in codeigniter?
Yes, the ->where() method can support that.
Since you do not want to cascade it:
$this->db->where('job_id', $job_id_var);
$this->db->where('job_name', $job_name_var);
->where() can handle array input as well:
$cond = array('job_id'=>$job_id_var, 'job_name'=>$job_name_var);
$this->db->where($cond); // here, only used once.
$query = $this->db->get('hello_table');
$result = $query->result_array();
return $result;

Eloquent ORM: count() remove the select(...)

I am using Eloquent ORM outside of Laravel-4 and I am building a custom Paginator.
First, I build a query using Fluent Query Builder. I want to get the number of result the query could return using count() and then I do a custom pagination using take(x) and skip(y). I need to do the count() before the take()->skip()->get() so I dont fall outside of the page range. The problem is that when I use the count() method on the query, it seems to remove any select I added previously.
I isolated the problem to this simple example:
$query = DB::table('companies')
->join('countries','companies.country_id','=','countries.id')
->select(
'companies.name as company_name',
'countries.name as country_name'
);
$nbPages = $query->count();
$results = $query->get();
//$results contains all fields of both tables 'companies' and 'countries'
If i invert the order of the count and get, it works fine:
$results = $query->get();
$nbPages = $query->count();
//$results contains only 'company_name' and 'country_name'
Question: is there a more elegant way the using something like this:
$tmp = clone $query;
$nbPages = $tmp->count();
$results = $query->get();
There is not, unfortunately. Open issue on github about the problem: https://github.com/laravel/framework/pull/3416

Doctrine and Symfony2: WHERE a.title LIKE $array

Hey I'm writing this post because I have few problem passing an array value in the doctrine query.
Here is the entire query as it is:
$data = $request->request->all();
$dql = "SELECT a FROM PfBlogBundle:Article a WHERE a.title LIKE '{$data['search']}' ORDER by a.id DESC";
If I print_r($data) I get the value so it's there somewhere. I just don't understand why it's not passing in the query.. Was expecting LIKE '{$data['search']}' to work but it doesn't.
From what I can tell by your snippet, you're looking for something like this:
$entityManager->getRepository('PfBlogBundle:Article')
->findBy(
array(
'key' => 'value'
)
);
Where key is the property/field and the value is the value to look for. Check the Symfony manual page. The bit you're after is Fetching Objects from the Database.
To use a like in the where clause, refer to this SO question, on how to use setParameter. You'll get your query with this:
$repo = $entityManager->getRepository('PfBlogBundle:Article');
$query = $repo->createQueryBuilder('a')
->where('a.title LIKE :title')
->setParameter('title', '%'.$data['search'].'%')
->getQuery();
Of course, add wildcards to suite your needs. I've enclosed the $data['search'] value in two % wildcards, which is slow, but then again: I don't know what you're actually doing. It might be that all you're after is the case-insensitive nature of LIKE, in which case the % can be left out all together...
Based on your previous questions (BTW: consider accepting an answer once in a while):
public function searchAction(Request $request)
{
$data = $request->get->all();
$repo = $this->getDoctrine()
->getRepository('PfBlogBundle:Article');
$query = $repo->createQueryBuilder('a')
->where('a.title LIKE :title')
->setParameter('title', '%'.$data['search'].'%')
->getQuery();
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query->getResults(),//get the results here
$this->requrest->get('page',1),
4
);
return $this->render('PfBlogBundle:Default:blog.html.twig', array('pagination'=>$pagination));
}
But this is just a crude fix, Google doctrine-symfony pagination, there are many detailed blog-posts on the matter

How to set wild card option in codeigniter like query with associative array?

As title says i can place '%' in a like query of Codeigniter
$this->db->like('title', 'match', 'before');
// Produces: WHERE title LIKE '%match'
for associative array
$array = array('title' => $match, 'page1' => $match, 'page2' => $match);
$this->db->like($array);
// WHERE title LIKE '%match%' AND page1 LIKE '%match%' AND page2 LIKE '%match%'
for more clarification my model has function which handles most of select query in i send an array parameter to retrieve results
function getTableData($table='', $fields='', $like=array(),$like1=array())
{
//Check For like statement
if(is_array($like) and count($like)>0)
$this->db->like($like);
if(is_array($like1) and count($like1)>0)
$this->db->or_like($like1);
//Check For Fields
if($fields!='')
$this->db->select($fields);
else
$this->db->select();
$result = $this->db->get();
//pr($result->result());
return $result;
}
This is my generic function so while sending as parameter or by modifying function how can i use wild card placing third parameter with default 'both' working as it is.
with third parameter i control the placing of % , But when i use a associative array how can i implement wildcard placing in Codeigniter.
How can i use it in associative array for different column.Is it possible?. I know i can use custom query and currently i m using it. For any help Thanks in advance.
I looked core DB_active_rec.php file. Please try this one:
$this->db->like($array, false, 'before');
/system/database/DB_active_rec.php line 571:
/**
* Like
*
* Generates a %LIKE% portion of the query. Separates
* multiple calls with AND
*
* #param mixed
* #param mixed
* #return object
*/
public function like($field, $match = '', $side = 'both')
{
return $this->_like($field, $match, 'AND ', $side);
}
use as many like as you need in your query. E.g:
$this->db->like('title', $title, 'after')->like('page1', $page1)->like('page2', $page2, 'after')->get('table');
You can use like() several times:
$this->db->like('title', 'match');
$this->db->like('page1', 'match');
$this->db->like('page2', 'match');
or if PHP >5 use chained:
$this->db->like('title', 'match')->like('page1', 'match')->like('page2', 'match');
if you have an array of values, use foreach():
//considering $like = array('field' => 'value', 'field2' => 'value2');
foreach ($like as $field=> $value)
{
$this->db->like($field, $value);
}

Categories