Doctrine select where equal to variable - php

This is what I want to do:
$query = $repository->createQueryBuilder('c')
->where('c.categoryParentid = ?', $pcategory->getcategoryId())
->orderBy('c.categoryId', 'ASC')
->getQuery();
$childcategories = $query->getResult();
The $pcategory->getcategoryId() is an integer. The where, is this correct?
I get this error:
ContextErrorException: Warning: get_class() expects parameter 1 to be object, integer given in /Applications/mampstack-5.4.20-0/apache2/htdocs/reuzze/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Expr/Base.php line 92

I haven't used that syntax before, but the Symfony docs have examples of using the query builder, and they show something like this:
$query = $repository->createQueryBuilder('c')
->where('c.categoryParentid = :pcategory')
->setParameter('pcategory', $pcategory->getcategoryId())
->orderBy('c.categoryId', 'ASC')
->getQuery();

You can also use the EntityRepository::findBy() method (outlined in the Symfony 2.x documentation here) which allows you to specify search criteria and sorting.
e.g.
$childCategories = $repository->findBy(array(
'categoryParentId' => $pcategory->getCatagoryId()
),
array(
'categoryId' => 'ASC'
)
);

Related

how to use like operator in array laravel 5.2?

I want to add Like operator in array but it gives me error:
Unknown column '0' in 'where clause (admin_id = 2 and 0 = name and Like = %zdgbdsh%) order by id asc limit 10 offset 0)
Here is my query:-
$conditions = array();
if(!empty($data['name'])) {
$conditions = array_merge($conditions,array('name','Like'=>'%'.$data['name'].'%'));
}
And here is my final query:-
$querys = DB::table('users')
->where($conditions)
->skip($iDisplayStart)->take($iDisplayLength)
->OrderBy($orderby,$dir)
->get();
Note: I don't want directly in query like
where('users.name','like','%'.$data['name'].'%');**
I want to do in conditions variable
I am using laravel framework 5.2
It should be:
$conditions=array_merge($conditions,array('name' => 'Like %'.$data['name'].'%'));
Update
I've just realised that will produce name = Like %data%
You can change it to:
$conditions=array_merge($conditions,array('name', '%'.$data['name'].'%'));
and in where use:
->where(join(' LIKE ', $conditions))
This is not the greatest way of applying multiple conditions, But you can always user the whereRaw
so loop through a array with your conditions eg.
$conditions = [];
if (!empty($data['name'])) {
$conditions = array_merge(
$conditions,
["name LIKE '%".$data['name']."%'"]
);
}
$query = DB::table('users');
// apply add raw conditions
foreach($conditions as $condition){ $query->whereRaw($condition); }
$query->skip($iDisplayStart)->take($iDisplayLength)
->OrderBy($orderby,$dir)
->get();
you could also find some packages that will help you out with things like this.
Hope it helps

How to pass array in where condition of Query with one "Not Equal" Condition

I am working on Laravel 5.2. I faced a problem for sending an array to model function with one on my value is Not Equal.
I check this way is working:
$users = DB::table('users')
->where([ ['status','1'], ['subscribed','!=','1'], ])
->get();
But in my case, i am working in a reusable function:
$whereData = array('name'=>'test' , 'id !=' => '5');
$users = DB::table('users')->where($whereData)->get();
Here Not Equal to condition not working and provides error. What is correct syntax for using this reusable function with whereData array consists of multiple operators like "!= , <> , etc ...".
I would suggest you the following way.
Only send the data without where condition.
Therefore,
$whereData = array('name'=>$username , 'statusid' => $userid);
$users = DB::table('users')->where('status', '=', $whereData['name'])->orWhere('subscribed', '<>', $whereData['statusid'])->get();
or as you mentioned, replace where with whereColumn
Thus the code will be,
$whereData = array( array('name','test') , array( 'id','<>','5'));
$users = DB::table('users')->whereColumn($whereData)->get();

Doctrine setParameter and Invalid parameter number

After many tries, I think I finally know the documentation by heart.
Then, I need your help .. I don't understand why Doctrine show me this error :
Invalid parameter number: number of bound variables does not match
number of tokens
Here is my code :
$qb = $this->em->createQueryBuilder();
$qb->select('m')
->from('Entities\Marque', 'm')
->leftJoin('m.magasin', 'ma')
->where('m.nom = :marque AND ma.nom LIKE :magasin')
->setParameter('marque', $marque)
->setParameter('magasin', '%'.$matchesNumber[1].'%');
$results = $qb->getQuery()->getArrayResult();
Thank you in advance for your answer.
This also happens if you accidentally use more than one where(), which happened to me once.
$em = $this->getEntityManager();
$query = $em->createQueryBuilder()
->from('AppBundle:SomeEntity', 's')
->select('s')
->where('s.foo = :foo')
->where('s.bar = :bar') // <- HERE
->setParameter('foo', 'Foo Value')
->setParameter('bar', 'Bar Value');
Should be:
$em = $this->getEntityManager();
$query = $em->createQueryBuilder()
->from('AppBundle:SomeEntity', 's')
->select('s')
->where('s.foo = :foo')
->andWhere('s.bar = :bar') // <- CHANGE TO andWhere()
->setParameter('foo', 'Foo Value')
->setParameter('bar', 'Bar Value');
Hope this helps someone.
I presume ->setParameter overrides the previous one.
For multiple Parameters use:
->setParameters(['key1' => $value1, 'key2' => $value2])
See Doctrine Upgrade:
From now on, parameters in queries is an ArrayCollection instead of a simple array. This >affects heavily the usage of setParameters(), because it will not append anymore parameters >to query, but will actually override the already defined ones. Whenever you are retrieving a >parameter (ie. $query->getParameter(1))
Doctrine Upgrade Description
Maybe that also applies to setParameter?
I'm so sorry .. I just found my error .. Later, like more later in my code .. I type a new query with my old "$qb" ..
I'm such a noob !
$qb = $this->em->createQueryBuilder();
$parameters = array('marque'=>$marque, 'magasin'=>'%'.$matchesNumber[1].'%');
$qb->select('m')
->from('Entities\Marque', 'm')
->leftJoin('m.magasin', 'ma')
->where('m.nom = :marque')
->andWhere('ma.nom LIKE :magasin')
->setParameters($parameters);
$results = $qb->getQuery()->getArrayResult();

Doctrine2 querystring query

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.

Doctrine 2 ORM problem setting parameters

I'm having a problem with a very simple query in Doctrine 2 ORM. I'm sure I've followed the docs to the letter, but it just won't work. I have this:
$qb = $this->em->createQueryBuilder()
->select('p')
->from('Property', 'p')
->where('type = :type');
$properties = $qb->getQuery()->setParameters(array(
'type' => 'house',
))->getResult();
And I get:
QueryException: [Semantical Error]
line 0, col 46 near 'type = :type':
Error: 'type' is not defined.
I've also tried:
$properties = $qb->getQuery()->setParameters(array(
':type' => 'house',
))->getResult();
With no luck. I'm sure this must be so simple, but I just can't see what's wrong.
Thanks.
->where('p.type = :type');
You always have to specify an owner of a property - Property entity in this case.
I've always done setParameter() on the QueryBuilder, not on the query.
Try
$qb = $this->em->createQueryBuilder()
->select('p')
->from('Property', 'p')
->where('type = :type');
$qb->setParameters(array('type' => 'house'));
$properties = $qb->getQuery()->getResult();

Categories