I'm new to Laravel framework and I'm looking for how to write Query in order to get the absolute value(in short ignoring the + and - sign and only display number from database.
I know we can use Abs in order to get it. But I don't know how do it.
Take a look at my code:
$users = DB::table('transaction_details')->
Join('ledger','transaction_details.ledger','=','ledger.Name')->
groupBy('ledger.Name')->select(
'ledger.CrDr as CrDr',
'transaction_details.ledger as Name',
'transaction_details.amount as Debit',
'ledger.OpeningBalance as openingBalance'
)->get();
In above query i want ledger.openingBalance value to be absolute.
How do I do that?
You can use DB::raw for the ledger.openingBalance select column to avoid it from being quoted by the Query Builder:
DB::table('transaction_details')
->join('ledger','transaction_details.ledger','=','ledger.Name')
->groupBy('ledger.Name')
->select(
'ledger.CrDr as CrDr',
'transaction_details.ledger as Name',
'transaction_details.amount as Debit',
DB::raw('ABS(ledger.OpeningBalance) as openingBalance')
)->get();
Related
I am trying to execute the following mysql query below with drupal 7 db_select. But I cant understand how this can be done. Is anyone can help me to translate the following mysql query into drupal 7 dynamic db query?
My main goal is actually sorting the mysql result by given string position in the name. Please keep in mind that i dont want to fetch all the results and sort them with php, instead I want to use mysql to do that. As i know the "ORDER BY LOCATE" command is doing that exactly.
SELECT name FROM `taxonomy_term_data` WHERE LOCATE('credit', name) > 0 ORDER BY LOCATE('credit', name)
1. Proper example of db_select
It is possible, using drupal 7 db_select, here is my example working code (done with help of this post)
My example in with table cities containing column city. Find cities with double "o" and sort by it's position:
$r = db_select('cities', 't')
->fields('t')
->condition('t.city', '%' . db_like('oo') . '%', 'LIKE');
$r->addExpression("LOCATE('oo', city) ", 'loc');
$r = $r->orderBy('loc', 'DESC')
->execute()
->fetchAllAssoc("id");
So similar in your example would be:
$r = db_select('taxonomy_term_data', 't')
->fields('t')
->condition('t.name', '%' . db_like('credit') . '%', 'LIKE');
$r->addExpression("LOCATE('credit', name) ", 'loc');
$r = $r->orderBy('loc', 'DESC'); //Or ASC
//Execute your query and gather result anyway you want.
2. Do you need to use db_select?
As someone stated in comment in link I posted "There are times and places to just use db_query."
I think this is that time :) Dont overcomplicate your code just to use drupal-way logic, which is often outdated or just too simple for complex tasks.
I think you should try something like this. db_like function seems to do what you are looking for.
$result = db_select('taxonomy_term_data', 'ttd')
->fields('ttd', 'name')
->condition('ttd.name, '%' . db_like('credit') . '%', 'LIKE')
->orderBy('ttd.name', 'DESC')
->execute();
Trying to get the sum of a int field in one of my table should be pretty easy, unfortunately it is not as I'm getting different result whether I use Laravel, MySQL or Excel.
Laravel 5.4 gives me 20506:
Table::sum('field_name');
MySQL gives me 1830:
Select sum(field_name) from table;
And the data from the Excel sheet before importing it into the database:
Sum gives me 145689
Any idea? I tried to cast to integer before doing the sum but it doesn't work.
All the numbers are pretty big but don't contain comma or dot.
Examples of values I have to sum: (contain sometimes empty cells)
17906774
99630157
28581131
159551532
20312892
668928885
$query = YourModel::query();
$query->withCount([
'activity AS yoursum' => function ($query) {
$query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid');
}
]);
You can use laravel aggregate function SUM as :
$result = DB::table('table_name')
->select(DB::raw('SUM(field_name) as total_field_name'))
->get();
For more details you can follow:
https://laravel.com/docs/5.4/queries
Thanks
Try with
$result = DB::table(tablename)
->selectRaw('sum(column)')
->get();
If it still gives you wrong result, maybe wait for someone to give you a better answer. This is all I could think of.
I have following issue.
I need to get rows from database where price is lower than given number.
I can do it this way:
DB::where('price', '<=', $given_number)->get();
but the problem is that inside price cell I have number with added signs like $ for dollars or Euro sign. I know how to parse the string in PHP to extract only numbers - filter_var($string, FILTER_SANITIZE_NUMBER_INT) , but how can I do this inside the query from Laravel? How can i pre-parse this 'price' attribute?
Is this what you mean?
$price = filter_var($given_number, FILTER_SANITIZE_NUMBER_INT);
$products = Product::where('price', '<=', $price)->get();
Is there more information that you left out?
My database (mysql) tables use TIMESTAMP columns, and whenever I want them returned in a query, I want them to be queried as "UNIX_TIMESTAMP(columnname)".
How do you easily modify queries in zend framework to achieve this?
For example, the current code is:
select = $this->select();
$select->where('user_id = ?',$user_id);
return $this->fetchAll($select);
This eventually becomes:
select * from tablename where user_id = 42;
I want something that automatically finds the TIMESTAMP column and changes the resulting query to:
select user_id,name,unix_timestamp(created) where user_id = 42;
I know I can use a MySQL view to achieve this, but I'd rather avoid that.
Thanks.
RR
You should be able to specify the fields you want in the select using the $select->from() object.
Zend_Db_Select
You should end up with something like this.
$select = $this->select();
$select->from(
array('t' => 'tablename'),
array('user_id', 'name', 'UNIX_TIMESTAMP(created)')
);
$select->where('user_id = ?',$user_id);
return $this->fetchAll($select);
If you wanted to run an expression that doesn't have parenthese in the function, Use the Zend_Db_Expr() method to escape the query properly.
I want to add a "CONVERT" stored procedure like this:
SELECT id, value, CONVERT(value, DECIMAL) AS ordred_value FROM test ORDER BY ordred_value;
to this collection query :
$collection = $this->getAssociatedProductCollection($product)
->addAttributeToSelect('*')
->addFilterByRequiredOptions()
->setPositionOrder()
->addStoreFilter($this->getStoreFilter($product))
->addAttributeToFilter('status', array('in' => $this->getStatusFilters($product)))
->addAttributeToSort('my_attribute', 'DESC');
for the purpose of ordering the associated products by my custom attribute "my_attribute" that have numeric values in text fields.
Thanks for help.
I'm not sure it's the bast solution, but you can do it like this:
<?php
$collection->getSelct()->columns(array('converted_value' => 'CONVERT(e.my_attribute, DECIMAL)'));
It will add a new column to result. Next sort the collection using it's select as above and the order method.