Doctrine DQL - Logic check in select - php

I am trying to use a LIKE comparison in a doctrine DQL in a MySQL database.
It works directly in SQL in the database and looks like this:
SELECT *, (name LIKE '%testO%') as partOfName
from organization
ORDER BY partOfName DESC;
This works just fine.
Now I try to implement this logic in Doctrine. My Querybuilder looks like this:
oQueryBuilder
->from(OrganizationEntity::class, organization)
->select('organization')
->addSelect('(organization.name LIKE %:searchTerm%) AS searchTermIsPartOfName')
->setParameter('searchTerm', $sSearchTerm)
->orderBy('searchTermIsPartOfName', 'DESC')
;
Trying to run it or get the SQL out of it gives me the following error:
[Syntax Error] line 0, col 97: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got 'LIKE'
It is definitely the part about the LIKE. I commented the last three lines out and it works.
How do I translate the above working SQL into Doctrine DQL?

LIKE expressions are covered under Conditional Expressions in DQL's grammar. And unfortunately, it's not possible to use these directly within a SelectExpression.
However you can use them within a CaseExpression, which can be used in a SelectExpression, and replicate the same behaviour:
->addSelect('CASE WHEN (organization.name LIKE :searchTerm) THEN 1 ELSE 0 END AS searchTermIsPartOfName')
->setParameter('searchTerm', "%{$sSearchTerm}%")
(there was also a minor issue about your LIKE expression - I'm pretty sure the % signs need to be part of the parameter value, not the query itself)

you forgot '' after LIKE, replace with string
->addSelect('(organization.name LIKE %:searchTerm%) AS searchTermIsPartOfName')
on
->addSelect('(organization.name LIKE \'%:searchTerm%\') AS searchTermIsPartOfName')

Related

Yii2 db query builder having into where

Sorry on my English. I add new condition to my query like this:
$query->andWhere(['or',
["<", "o.score", $score_operator],
["<", "d.score", $score_delivery],
["<", "SUM(sd.score)/count(DISTINCT sd.id)",$score_dishes]]);
Buth I got error:
General error: 1111 Invalid use of group function
Then I read that I must use having in 3-d row, but I don't know how to put "having" in "where" condition.
For condition/filter related to aggregation function you should use having and not where
$query->having("SUM(sd.score)/count(DISTINCT sd.id) < " .$score_dishes);
where work on table rows having work on selected result rows.
http://www.yiiframework.com/doc-2.0/yii-db-query.html#having()-detail
starting for 2.0.11 you could use also filteHaving in case you having http://www.yiiframework.com/doc-2.0/yii-db-query.html#filterHaving()-detail

Eloquent whereRaw statement and orWhereRaw is NULL

For a search query I have the following:
DB::whereRaw('column = ?', 'foo')->orWhereRaw('column IS NULL')->get();
Adding the orWhereRaw statement gives me less results than only the whereRaw. Somehow it seems to ignore the first when adding the other. It is included in the SQL statement. Is there another way to compare for a string and null value?
I have also tried the following, as suggested below:
return self::select('id')
->where('current_state', 'unavailable')
->orWhereNull('current_state')
->get();
If I change the order (the whereNull first and the where second) this also gives me different results. It appears as if the inclusive query doesn't function correctly in correspondence with the where clause. If I use to regular where clauses I don't experience any issues.
Running SELECT * FROM events WHERE current_state='unavailable' OR current_state IS NULL; does produce the correct result for me.
Don't use whereRaw to check for null. You can use this instead:
->orWhereNull('column')
The proper way to do the first where, unless you're doing something extra such as a mysql function, is just to pass the column along like this:
where('column', '=', 'foo')
You can actually eliminate the equals, since it defaults to that. So your query would be:
DB::table('table')->where('column', 'foo')->orWhereNull('column')->get();

Query in PHP with 'and' or 'or' as variable

I would like to do search for advanced search. The Search feature has and/or for every category. User can choose any combination of and n or. Here i give the screenshot
I store the and/or into variable call $pil, $pil1,$pil2 and $pil3. And will put them in query. it's better than validate one by one every condition of and/or
So this is my query using postgresql in PHP
$query = pg_query("SELECT evaluationdate,onlinename,channel,topik,reviewername,sourceevaluation,evaluation
from AgentPerformance
where onlinename like '%".$VEOn1."%'
".$pil." reviewername like '%".$VERev1."%'
".$pil1." channel like '%".$VEChan1."%'
".$pil2."sourceevaluation like '%".$VESource1."%'
".$pil3."evaluationdate between '".$VEStart1."' and '".$VEEnd1."'");
EDIT :
The problem now, All the variables must not be empty or the query will be error. any way to trick this?
You've missed some spaces near sourceevaluation and evaluationdate
Try with this query :
$query = pg_query("SELECT evaluationdate,onlinename,channel,topik,reviewername,sourceevaluation,evaluation
from AgentPerformance
where onlinename like '%".$VEOn1."%'
".$pil." reviewername like '%".$VERev1."%'
".$pil1." channel like '%".$VEChan1."%'
".$pil2." sourceevaluation like '%".$VESource1."%'
".$pil3." evaluationdate between '".$VEStart1."' and '".$VEEnd1."'");
Simply. Use validation for each $pil whether it is empty or not. it makes me validate 4 times, but it solves the problem. The syntax error has been solved too

Laravel Fluent Query Builder Update Query

I want to add two columns while using update, like this:
Update purchase_stock inner join stock on purchase_stock.fkstockid=stock.stockid SET currentavailable=currentavailable+subquantity where fkorderid='1';
Here is the current Fluent code:
DB::table('purchase_stock')->join('stock','stock.stockid','=','purchase_stock.fkstockid')->where('fkorderid',$orderId)->update(array('currentavailable'=>'currentavailable'+'subquantity'));**
But it throws error as below:
"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"syntax error, unexpected '=>'"
Does any one have solution?
You were very close with your fluent attempt, but there were two issues:
The plus sign needs to be inside the quotes, since you want the math done in SQL, not in PHP.
Need a DB::raw() around the value so Laravel doesn't think you're actually trying to set it to the string "currentavailable + subquantity"
So the final product looks like this:
DB::table('purchase_stock')
->join('stock', 'stock.stockid', '=', 'purchase_stock.fkstockid')
->where('fkorderid', $orderId)
->update(['currentavailable' => DB::raw('currentavailable + subquantity')]);
Мaybe you need to set these two fields from which tables. Exampl. DB::table('purchase_stock')->join('stock','stock.stockid','=','purchase_stock.fkstockid')->where('fkorderid',$orderId)->update(array('stock.currentavailable'=>'stock.currentavailable'+'stock.subquantity'));
Ohk!
I already tried this one but it is not working
As of now I am using DB::statement('') and it's working
So I have written whole update query within statement and it's working as somewhere I have read that it will not be helpful to return result set but will work with insert or update.

How do I use CONCAT_WS together with IN?

Using Symfony2 and Doctrine2, want to combine CONCAT_WS with IN, rather than write a lot of IF's.
WHERE CONCAT_WS('-', id2, id2) IN ($ids)
I am receiving this error:
[Syntax Error] line 0, col 446: Error: Expected Doctrine\\ORM\\Query\\Lexer::T_IN, got '('
$ids are in form of '123-456'.
If I simply use a column instead of CONCAT_WS, it works:
WHERE id2 IN ($ids)
Not all MySQL functions are available for use in Doctrine. Only those functions that are common to all databases supported are available.
Follow this link to see the list of functions available by default http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#functions-operators-aggregates .
If you want to use CONCAT_WS anyway, read about creating custom functions on the following links. You can create your own DQL Custom Function and will be able to use just like you tried before.
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/dql-user-defined-functions.html
http://symfony.com/doc/current/cookbook/doctrine/custom_dql_functions.html
I've had the same problem as this, I solved it using this:
CONCAT(CONCAT('-', id2), id2)
Not the most elegant solution but it works. Writing a custom function is the way to go.

Categories