How to use IS NOT NULL in Associative Array - php

I am new in Symfony framework And I want to use Query basis on Condition
which is using associative array and I want to use IS NOT NULL But it is not
working.
$repository = $this->getDoctrine()->getRepository('AppBundle:Order');
$order = $repository->findBy(array('status' => $last_status,'new_coloumn_id'=>"IS NOT NULL"));
How to use IS NOT NULL in array.

You should add custom function into your Order Repository file(class). Example;
public function getOrderStatus($last_status = NULL){
$query = $this->createQueryBuilder('order')
->where('order.new_column_id IS NOT NULL')
->andWhere('status = :status')
->setParameter('status', $last_status);
return $query->getQuery()->getResult();
}
And you can use it;
$order = $this->getDoctrine()->getRepository('AppBundle:Order')->getOrderStatus($last_status)

Try this in your repository class:
public function findOrder($last_status){
$qb = $this->createQueryBuilder('order');
return $qb->where($qb->expr()->isNotNull('order.new_column_id'))
->andWhere($qb->expr()->eq('order.status',':last_status'))
->setParameter('last_status',$last_status)
->getQuery()
->getOneOrNullResult();//getArrayResult,getResult()
}
hope it helps...

Related

Dynamically update repository queries

I've created a query in a repository.
I want to change some elements in this query (like where condition, sort, etc) thanks to parameters sent via the function.
This function works and returns data :
public function dashboardIndex($offset, $limit, $order)
{
$query = $this->createQueryBuilder('v')
->setFirstResult($offset)
->setMaxResults($limit)
->getQuery()
->getResult()
;
return $query;
}
Adding dynamic "addOrderBy" doesn't work and it doesn't return data
public function dashboardIndex($offset, $limit, $order)
{
$query = $this->createQueryBuilder('v');
/* Sort dynamically $order = ['column1' => 'ASC', 'column2' => DESC, ...] */
foreach($order as $column => $direction){
$query->addOrderBy('v.'.$column , $direction);
}
/* Sort dynamically */
$query->setFirstResult($offset)
->setMaxResults($limit)
->getQuery()
->getResult()
;
return $query;
}
"createQueryBuilder" returns an object, but cannot it be modified all along the function?
Obvious statement is obvious:
To return the result of a query, you have to return the result of the query.
hence return $query; doesn't return the result, but the query.
better:
return $query->getQuery()->getResult();

Laravel conditional clause when for filtering value

I have a event table with status o or 1.
I have to filter the event with status 1,0 or ALL.
I tried with laravel when conditional clause,its not working with value zero,other conditionals are working.
$status = Input::get('status');
$events = DB::table('events')
->select('events.*')
->when($status, function ($query) use ($status) {
return $query->where("events.status",$status);
})
->get();
in_array function used in when method try this one
because 0(zero) means(false) by default understand so try to use inner function in when method
if didn't pass status then set default value as 2 or any number but not 0,1 and null
$status = Input::has('status') ? Input::get('status') : 2;
$events = DB::table('events')->select('events.*')
->when(in_array($status,[0,1]), function ($query) use ($status) {
return $query->where("events.status",$status);
})->get();
second way create a new function
function checkStatus($status,$array) {
if(isset($status)) {
return in_array($status,$array);
}
return false;
}
$events = DB::table('events')->select('events.*')
->when(checkStatus($status,[0,1]), function ($query) use ($status) {
return $query->where("events.status",$status);
})->get();
For any future reader using 0 and 1
we can use when in the following way
->when($request->has('status'),
fn ($query) => $query->where("status", $request->status)
)->get();
we are getting the user requested status using has method in Laravel to deal with it.

Form with variable number of criterias on Symfony4 / Doctrine2

Let's take https://symfony.com/doc/current/forms.html#building-the-form example form but only for Search in tasks list instead of save.
Goal is to allow searches on task, dueDate or both criterias (in my real case, I have 9 criterias)
Here are src/Repository/ResultRepository.php :
class ResultRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Result::class);
}
public function findMultiKeys($task, $dueDate): array
{
$qb = $this->createQueryBuilder('d')
->andWhere('d.task = :task')
->setParameter('task', $task)
->andWhere('d.dueDate = :dueDate')
->setParameter('dueDate', $dueDate)
->getQuery();
return $qb->execute();
}
}
It require both criterias to return result(s)!
I ran a lot of searches and find:
How do I use a complex criteria inside a doctrine 2 entity's
repository?
Symfony2/Doctrine QueryBuilder using
andwhere()
Doctrine2 doc - setParameters method
So I code a $where_string variable to construct my variable where.
and a $parameters to construct my variable parameters array, and my findMultiKeys becomes:
public function findMultiKeys($get_form): array
{
$where_string = '';
$parameters = [];
$task = $get_form->getTask();
if ($task !== null) {
$where_string .= "d.task = :task";
$parameters += array('task' => $task);
}
$dueDate = $get_form->getDueDate();
if ($dueDate !== null) {
if ($where_string !== '')
$where_string .= " AND ";
$where_string .= "d.dueDate = :dueDate";
$parameters += array('dueDate' => $dueDate);
}
$qb = $this->createQueryBuilder('d')
->where($where_string)
->setParameters($parameters)
->getQuery();
return $qb->execute();
}
It works, perhaps not the best way?
In my searches, I found, of course, to use ElasticSearch, perhaps to much to my simple need, or I found PetkoparaMultiSearchBundle
Bests solutions welcomes
I have a proposition :-)
You can build an task4Seach entity with your 9 criteria (without
persistance)
create a form type with this "data_class"
use it to get your datas in your repository
$qb = $this->createQueryBuilder('d');
...
if ($task4Seach ->getDueDate()) {
$qb->andWhere($qb->expr()->eq('d.dueDate', ':dueDate'));
$qb->setParameter('dueDate', $task4Seach->getDueDate());
}

how to use ObjectId inside $in query in MongoDB?

I have the following query in MongoDB
$this->createQueryBuilder()
->field('actor')->in($actorIdArray)
->getQuery()
->execute();
where the field actor is an object reference with annotation
#MongoDB\ReferenceOne(targetDocument="User", simple=true)
which means it will store the object Id instead of the full reference.
When $actorIdArray is an array of id with the form
["5706cb39821b166d3931f34f", "56015f7d4f8bd90b769e6e75"]
the query does not return nothing, which is the expected since the filed actor contains object id.
However, if I build the array this way
[new MongoId("5706cb39821b166d3931f34f"), new MongoId("56015f7d4f8bd90b769e6e75")]
it doesn't work either, which is quite surprising for me.
The log shows the query is made
{ "actor": {"$in":[{"$id":"5706cb39821b166d3931f34f"},{"$id":"56015f7d4f8bd90b769e6e75"}]}}
and I think it should be something like this
{ "actor": {"$in":[ObjectId("5706cb39821b166d3931f34f"),ObjectId("56015f7d4f8bd90b769e6e75"]}}
Not sure if I am doing something wrong,
any ideas?
As you can see in code source of Doctrine\ODM\MongoDB\Query\Builder -> references method:
public function references(object $document) : self
{
$this->requiresCurrentField();
$mapping = $this->getReferenceMapping();
$reference = $this->dm->createReference($document, $mapping);
$storeAs = $mapping['storeAs'] ?? null;
$keys = [];
switch ($storeAs) {
case ClassMetadata::REFERENCE_STORE_AS_ID:
$this->query[$mapping['name']] = $reference;
return $this;
.....
return $this;
}
You must know how the reference is built. Usually, this is by $id.
Use actor.$id as the field name:
$dm = $this->get('doctrine.odm.mongodb.document_manager'):
$documents = array();
foreach($actorIdArray as $id){
$documents[] = new MongoDB\BSON\ObjectId($id);
}
$this->createQueryBuilder()
->field('actor.$id')->in($documents)
->getQuery()
->execute();
Doctrine wants your array to be an array of documents.
You can load document references without query.
$dm = $this->get('doctrine.odm.mongodb.document_manager'):
$documents = array();
foreach($actorIdArray as $id){
$documents[] = $dm->getReference('AppBundle:Actor',$id); // <- this is the key
}
$this->createQueryBuilder()
->field('actor')->in($documents)
->getQuery()
->execute();

Laravel conditions in Controller where clause

I'm trying to build a query based on URL parameters. When the Controller is loaded I need to check which parameters have been provided and build a query from them. It's working with static values, but isn't working with conditional statements. Is my laravel syntax correct?
class OrdenesController extends BaseController {
public function showOrdenes($action)
{
$my_id = Auth::user()->id;
$my_cod = Auth::user()->codprov;
switch ($action)
{
case 'list':
$rows = DB::table('ordens')->count();
if(Input::get("jtSorting"))
{
$search = explode(" ", Input::get("jtSorting"));
$numorden= Input::get("nro_orden");
$filtros =explode(" ", $filtros);
$data = DB::table("ordens")
->select(array('*', DB::raw('SUM(cant_pend) as cant_pend'), DB::raw('SUM(importe) as importe')))
->where('cod_prov', '=', $my_cod)
->where('nro_orden', '=', $numorden)///work
---------- ////no work
if (Input::has('nro_orden')) {
->where('nro_orden', '=', $numorden)
}
---------- /// no work
->groupBy('nro_orden')
->skip(Input::get("jtStartIndex"))
->take(Input::get("jtPageSize"))
->orderBy($search[0], $search[1])
->get();
}
return Response::json(
array(
"Result" => "OK",
"TotalRecordCount" => $rows,
"Records" => $data
)
);
break;
};
}
}
You are missing the variables, no? You haven't told PHP what variable/object to do the where() to in your condition. The magic of Laravel's Eloquent (and a lot of other libraries) is that when you call its methods, it returns itself (the object) back so you can make another method call to it right away.
So when you do this:
$data = DB::table("ordens")
->select(...)
->where(...);
is the same as:
$data = DB::table("ordens");
$data = $data->select(...);
$data = $data->where(...);
But you are trying to do ->where(...) right away after if condition. You need to tell PHP which object/variable you are trying to call the method from. Like this:
$num = Input::get("nro_orden");
$data = DB::table("ordens")
->select(array('*', DB::raw('SUM(cant_pend) as cant_pend'), DB::raw('SUM(importe) as importe')))
->where('cod_prov', '=', $my_cod);
if (Input::has('nro_orden')) {
$data = $data->where('nro_orden', '=', $num);
}
$data = $data->groupBy('nro_orden')
->skip(Input::get("jtStartIndex"))
->take(Input::get("jtPageSize"))
->orderBy($search[0], $search[1])
->get();

Categories