I am using a doctrine 2 in symfony3.4 and I have a complex query which is :
$query = $this->createQueryBuilder(
'SELECT id FROM AppBundle:Room WHERE id NOT IN ( SELECT room_id FROM AppBundle:Bookings WHERE NOT ( checkOut <= :check_in OR checkIn >= :check_out ) ) ORDER BY id'
)
->setParameter('check_in', $request->query->get('check-in'))
->setParameter('check_out', $request->query->get('check-out'))
->getQuery();
return $rooms = $query->execute() ;
my problem is when I execute this query , I get an error which is :
[Syntax Error] line 0, col 7: Error: Expected IdentificationVariable | ScalarExpression | AggregateExpression | FunctionDeclaration | PartialObjectExpression | "(" Subselect ")" | CaseExpression, got 'SELECT'
The createQueryBuilder method expects a string as first parameter but you are providing a full query statement and the result would be something like this:
select select id... from table
an that raises an exception the bold part is your query inside the createQueryBuilder method.
Try this instead:
$this->createQueryBuilder('alias')->addSelect('alias.id')
->where(...)
->orderBy(...)
Hope it helps
EDIT
inside the where you put what is after the where in your old code but with the query builder you can build your query without the sql and let doctrine build the query for you
check this doc
Related
update fare_strategy set sales_date_to = ’07-SEP-22’
where dep_date_to is not null
and market_id in
(select market_id
from fare_strategy_markets
where set_type = ‘STANDARD’
);
In the following query, I'm getting error as SQL command not properly ended.
try to change like this because in your query you used ’ this is not valid so i just change it to ' so it's works fine
update fare_strategy set sales_date_to = '07-SEP-22' where dep_date_to is
not null and market_id in (select market_id from
fare_strategy_markets where set_type = 'STANDARD');
Here is my sql, i am struggling to translate this to laravel 5.8 query builder syntax.
SELECT CC AS CountOfVisits, Count(CC) AS Users
FROM
(
SELECT user_id, count(user_id) AS CC FROM mytable
GROUP BY user_id
) AS CC
GROUP BY CC;
I tried this:
$frequency= DB::connection('mysql2')
->select(DB::raw('CC AS CountOfVisits'), DB::raw('Count(CC) AS Users'))
->from(function($sq)
{
$sq->select(DB::raw('user_id, count(user_id) AS CC FROM '))
->from('mytable')
->groupBy('user_id');
})
->groupBy('CC')
->get();
it errors with
Argument 1 passed to Illuminate\Database\Connection::prepareBindings()
must be of the type array, object given, called in
/var/app/portal/vendor/laravel/framework/src/Illuminate/Database/Connection.php
on line 665
Any help would be great thanks
I think the problem you're having is that the returned connection is expecting string for the full query with additional bindings on the second parameter. You can still build it using illuminate's query builder first if you like, then run the select using the generated string.
$query = DB::query()
->select('CC AS CountOfVisits', DB::raw('count(CC) AS Users'))
->fromSub(function (\Illuminate\Database\Query\Builder $query) {
$query->select('user_id', DB::raw('count(user_id) AS CC '))
->from('mytable')
->groupBy('user_id');
}, 'CC')
->groupBy('CC');
$result = DB::connection()->select($query->toSql());
I am working on Grails 2.4.0. I want to execute the native query in Groovy Controller. The query is as follow:
SELECT AVG(REPLACE(n.ep_text, 'PPM', '')), MONTH(n.date_creat)
from notification n
where n.type = 42
GROUP BY MONTH(n.date_creat)
Firstly, I execute the above query but it's have not found the REPLACE function like:
String query1 = "SELECT n.id, avg(REPLACE(n.epText, 'PPM', '')) FROM Notification as n";
def result = Notification.executeQuery(query1.toString())
How can I able to execute the REPLACE function in it?
And secondly, I have some R&D on it, but to execute the native query to required the sessionFactory. Unable to understand how to get the current session of Hibernate in Grails 2.4.0 to execute the native query?
Any help would be appreciated.
In order to use a native query, we can use SessionFactory, which is a bean and we can simply declare it to our Grails controller or service and dependency injection will handle it. Here is sample code using this bean to execute a native query.
class PublicService {
def sessionFactory
def getMatchedValue(){
def currentSession = sessionFactory.currentSession
def q = "select bank.id as id, bank.credit_amount as creditAmount, bank.debit_amount as debitAmount, bank.transaction_date as transactionDate, bank.transaction_name as transactionName, receipt.cr_date as crDate, receipt.picture_reference as pictureReference, receipt.receipt_date as receiptDate, receipt.reimbursment as reimbursment, receipt.total_amount as totalAmount, receipt.vendor as vendor " +
"from bank inner join receipt on bank.debit_amount=receipt.total_amount where ((bank.transaction_date >= receipt.receipt_date) and (bank.transaction_date <= DATE_ADD(receipt.receipt_date, INTERVAL 5 DAY) ))"//sample native query
def data = currentSession.createSQLQuery(q)
data.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);//if you are using alias for query e.g bank.credit_amount as creditAmount
final result = data.list()
return result
}
}
I have a query that i want it to be executed in a condition, for instance the api key .
Human :
If Api key is in the Api database, do the following query, say 'You Are Not Allowed' .
What i tried :
Select IF ( api.key = 'myapikey' , TrueQuery , 'You are not allowed') from api
My problem is in the query, i'm getting a lot of errors, the query contains " SELECT ... FROM ... WHERE ... GROUP BY ... LEFT JOIN " .
What's the way to accomplish it ?
Following example returns null :
SELECT CASE WHEN (SELECT api.app FROM api WHERE api.app = 'Test' )
THEN (SELECT items.rom_id FROM items)
END
Try this, without using IF, but using EXISTS.
select *
from ( TrueQuery ) t
where exists(select 1 from api where api.key = 'myapikey')
I am trying to use the following query in SQL Server
SELECT [AL].[Subscriptions].Id,
[AL].[Subscriptions].name,
[AL].[Subscriptions].description,
[AL].[Subscriptions].price,
[AL].[Subscriptions].iconFileName,
IIf(a.expiryDate > Now(), 'TRUE', 'FALSE') AS isSubsByUser
FROM [AL].[Subscriptions]
LEFT JOIN (SELECT *
FROM [AL].[UserSubscriptions]
WHERE userId = 13259) AS a
ON Subscriptions.Id = a.itemid;
but always get the error
Error in list of function arguments: '>' not recognized.
Unable to parse query text.
How do I resolve it?
Like Martin Smith said you need to use a case statement. Also it looks like you are only using a couple of fields in the derived table therefor I would suggest not using *. I put a example below.
SELECT [AL].[Subscriptions].Id,
[AL].[Subscriptions].name,
[AL].[Subscriptions].description,
[AL].[Subscriptions].price,
[AL].[Subscriptions].iconFileName,
case when a.expiryDate > GetDate() then 'TRUE' else 'FALSE' end AS isSubsByUser
FROM [AL].[Subscriptions]
LEFT JOIN (SELECT expiryDate, itemid
FROM [AL].[UserSubscriptions]
WHERE userId = 13259) AS a
ON Subscriptions.Id = a.itemid;