Laravel db::select() returns one string result - mysql

I'm trying to make a select using laravel and return with a response-json, i try:
public function verificaQuantidadeAnimaisAprovar(){
$quantidade_pets_aprovar = DB::select('SELECT (SELECT SUM(animal_pendente) FROM cademeupet.animais_adocao) +
(SELECT SUM(animal_pendente) FROM cademeupet.animais_encontrados) +
(SELECT SUM(animal_pendente) FROM cademeupet.animais_perdidos)
FROM DUAL '
);
return response()->json($quantidade_pets_aprovar, 201);
}
In the bd i have this result when i run this query:
but when i run my api in postman i receive:
[{"(SELECT SUM(animal_pendente) FROM cademeupet.animais_adocao) +\r\n
(SELECT SUM(animal_pendente) FROM cademeupet.animais_encontrados) +
\r\n (SELECT SUM(animal_pendente) FROM
cademeupet.animais_perdidos)":"36"}]
I need only the number result query: 36.
How i can fix this?

You are passing a whole SQL expression inside of the select method, which is designed to perform a select sql operation.
You should probably use the raw expression which is designed to handle complete sql queries :
public function verificaQuantidadeAnimaisAprovar(){
$quantidade_pets_aprovar = DB::raw('SELECT (SELECT SUM(animal_pendente) FROM cademeupet.animais_adocao) +
(SELECT SUM(animal_pendente) FROM cademeupet.animais_encontrados) +
(SELECT SUM(animal_pendente) FROM cademeupet.animais_perdidos)
FROM DUAL '
);
return response()->json($quantidade_pets_aprovar, 200);
}
Note : I also changed the http code of your response because 201 (Created) indicates the creation of something, which does not seem to happen here. 200 (Ok) seems more appropriate. Be free to put 201 back if this operation creates something in your database.
Let me know if it helped you :)

Related

SQL run command if row exists

I'm new to MySQL and I'm trying to make the following pseudocode work:
SELECT IF(
EXISTS(SELECT * FROM users WHERE `email`="admin" AND `token`="blablabla"),
(UPDATE * FROM sometable WHERE `var`="notimportant"),
"NOT_AUTHORIZED");
What I'm trying to achieve is running code based on the presence of a row, and if it doesn't exists return a message, or something usable. If it does exists, run another SQL command instead, and return those results.
Is this possible?
Your intent is a bit hard to follow from the invalid syntax. But the gist of your question is that you can use a where clause:
UPDATE sometable
SET . . .
WHERE var = 'notimportant' AND
EXISTS (SELECT 1 FROM users WHERE email = 'admin' AND token = 'blablabla');
You can also represent this as a JOIN. Assuming the subquery returns at most one row:
UPDATE sometable t CROSS JOIN
(SELECT 1
FROM users
WHERE email = 'admin' AND token = 'blablabla'
LIMIT 1
) x
SET . . .
WHERE var = 'notimportant' ;

How to write a native SQL query in Grails 2.4.0?

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
}
}

Using IF And Executing A Query If It's True

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

SQLSTATE[HY000]: General error with MySQL variable in ZF1

I have a MySQL query that works perfectly in PhpMyAdmin but throws an SQLSTATE[HY000]: General error when using within Zend Framework 1.12 and its fetchAll() method. Here it is:
SET #csum := 0;
SELECT s1.Date, (#csum := #csum + s1.total) as cumulative_sum
FROM (
SELECT c.datefield AS Date, IFNULL(SUM(subscription_total),0) AS total
FROM subscription s
RIGHT JOIN calendar c
ON c.datefield = DATE(subscription_date)
WHERE (c.datefield BETWEEN
(SELECT MIN(DATE(subscription_date)) FROM subscription)
AND
NOW()
)
GROUP BY DATE
) AS s1
The statement doesn't return any error if I remove the SET statement but I need to set a MySQL variable otherwise cumulative_sum will just be NULL values. Here is the code of the method:
public function findCumulativeCashflow($statut)
{
$db = $this->_getDbTable();
$dbAdapter = new Zend_Db_Adapter_Pdo_Mysql($db->getAdapter()->getConfig());
$sql = '<SQL statement above>';
$statement = $dbAdapter->query($sql);
$rows = $statement->fetchAll();
return $rows;
}
The error points the $rows = $statement->fetchAll(); line, is there another ZF method to use with SET #var := value?
Any ideas would be much appreciated.
Thanks!
As per this question, I need to use another query as fetchAll() cannot handle multiple queries.
I therefore need to set the MySQL variable with $dbAdapter->query('SET #csum := 0;'); and then do the main query.

IF condition in mysql

I have a contact table I wish to query when a certain condition exists. I tried the query below but am getting a syntax error.
SELECT *
FROM contact_details
WHERE contactDeleted` =0
AND IF ( contactVisibility = "private"
, SELECT * FROM contact_details
WHERE contactUserId = 1
, IF( contactVisibility = "group"
, SELECT * FROM contact_details
WHERE contactGroup = 3
)
)
If I'm understanding your question correctly (which is difficult with the lack of info you've provided. Sample datasets and expected outcomes are typically helpful), then I don't believe you need IFs at all for what you want. The following will return contacts that are not deleted and who either have (visibility = "private" and userId = 1) OR (visibility = "group" and group = 3)
SELECT *
FROM contact_details
WHERE contactDeleted = 0
AND (
(contactVisibility = "public")
OR
(contactVisibility = "private" AND contactUserId = 1)
OR
(contactVisibility = "group" AND contactGroup = 3)
)
I am assuming you want to use the IF() function and not the statement which is for stored functions..
Refer to this link for more information on that.
Notice that you have put 2 select statements in there, where the custom return values are supposed to be. So you are returning a SELECT *... now notice that in your upper level sql statement you have an AND.. so you basically writing AND SELECT *.. which will give you the syntax error.
Try using .. AND x IN (SELECT *) .. to find if x is in the returned values.
Let me also list this link to make use of an existing and well written answer which may also applicable to your question.