How do I use CONCAT_WS together with IN? - php

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.

Related

Error when using selectRaw() Laravel method with parameter binding

I'm trying to run this: $query->selectRaw('count(?)', [$column]) on Laravel 7.0, but gives me an error:
SQLSTATE[42P18]: Indeterminate datatype: 7 ERROR: could not determine data type of parameter $1.
PS: $column is a string.
When I put count(distinct ?), it results in wrong count.
I already tried "{$column}" and '%'.$column.'%', but it didn't work.
I tried other ways for hours, until I ask in a community and someone answered me that it's not possible to do this. The binding will only works with column values or something like that, despite that it doesn't have detailed uses of the selectRaw method.
Well, I've lost many hours, so I gave up and went to my objective with another approach.
You can use param in selectRaw by using quotes
Example:
$column = 1;
$query->selectRaw('count(**$column**)');

How cant I use Doctrine + convert_tz()

I'm trying to use convert_tz for order by my query. When I run it on mysql it works perfect but when I use it with the ORM of my application It does not work. There's a right way to write it on my code?
Here is my actual code:
$qb->select('table1');
$qb->from('Entities\Table1', 'table1');
$qb->orderBy("CONVERT_TZ(concat(table1.date, ' ', table1.hour), table1.timezone, 'America/Sao_Paulo')", "asc");
$qb->getQuery()->getResult();
That's a MySQL-specific function which isn't defined in DQL.
If you must use it then you'll have to use native queries or install something like the DoctrineExtensions library, which claims to add support for CONVERT_TZ().

Doctrine DQL - Logic check in select

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')

Using two columns in where Laravel ORM

I have two columns in my table: max and current. I want to build simple scope
public function scopeNotMax($query)
{
return $query->where('max', '>', 'current');
}
But Laravel gives me that query:
SELECT * FROM table WHERE `max` > 'current'
I don't want this result and I know that I can use in this place whereRaw() or DB::raw(). But I can't find another way to say "hey, this is column, not string!'. Can I do it? Or I must use raws? I want to avoid it.
There is no other way.
where() method in this case add third parameter (value) to bindings and passes it ot PDO library. So it will be escaped.
Alternatively You can pass as third parameter a Closure, but then laravel will form a sub-select for You, which doesn't helps much.
Looks like whereRaw() is made for this kind of sitiuation.
Did you give a try with this ? return $query->where('max > current');
you can use whereRaw():
->whereRaw('table_1.name = table_2.name');
You exmaple code:
->whereRaw('max>current');

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.

Categories