Arithmetic operations in select with CodeIgniter - codeigniter

I´m triying to do an arithmetic operation but i always get error.
This is the query:
public function getAllModifiers($condition)
{
$this->db->select('DM.id AS modifier_id, DM.name, minimum, maximum');
$this->db->select('DMI.id AS item_id, DMI.name AS item_name, `DMI.price * 1.1` AS item_price');
$this->db->from('dishes_modifiers DM');
$this->db->join('dishes_modifiers_items DMI', 'DMI.modifier_id = DM.id', 'left');
$this->db->where($condition);
return $this->db->get()->result();
}
How can i get the item_price * 1.1?
Thanks.

The backticks are used to escape object names (e.g., columns names). Any mathematical operation should be outside this escaping:
$this->db->select(`DMI.price` * 1.1 AS item_price');
# Here -----------^---------^

Check this:
$this->db->where($condition);
This one not checking the data with the database values.

You can use this in where condition
(DMI.price *1.1) > DMI.price *1.1

Related

How to select min and max in laravel

I want to convert this code in laravel.
SELECT MAX(date_start) AS DateStart,MIN(date_end) AS DateEnd FROM DBTest
And I try this code
$data = DB::table('DBTest')
->select(max('date_start'), min('date_end')))
->get();
Return Error: max(): When only one parameter is given, it must be an array
I am using laravel 5.2, and SQLyog as database
I am confuse in syntax please help me
You can't use functions in select statement, but you can use raw SQL :
$data = DB::table('DBTest')
->select(\DB::raw('MIN(date_start) AS DateStart, MAX(date_end) AS DateEnd'));
->get();
You can do it like this:
For the max start date:
max = DB::table('DBTest')->select('date_start')->orderBy('date_start', 'desc')->first();
For min end date:
min = DB::table('DBTest')->select('date_end')->orderBy('date_end', 'asc')->first();
You have to use something called selectRaw method in Laravel in order to achieve this result. Chaining method like ->max('columnA')->min('columnB') will not work. So, here is the solution:
$data = DB::table('DBTest')
->selectRaw('MAX(date_start) AS DateStart, MIN(date_end) AS DateEnd')->get();
Try MIN() and MAX() functions in the sql query.
$data = DB::table('DBTest')
->select(\DB::raw('MIN(date_start) AS startDate, MAX(date_end) AS endDate'));
->get();

How to use sum() with join and group by statement

I want to sum of amount by currency wise
I do in SQL like this
select sum(total),currencies.currency_symbol from invoices
join(currencies)
where(invoices.currency_id = currencies.id)
group by(currency_id)
I tried in Laravel like this
$sum = Invoice::sum('total')
->select('currency_symbol')
->join('currencies','invoices.currency_id','=','currencies.id')
->groupBy('currency_id');
return response()->json($sum);
But it throws an error
Symfony\Component\Debug\Exception\FatalThrowableError: Call to a member function select() on string
please give me solution
I think you have to use selectRaw, because the combination of sum and select i don't think will work, you can use one of the two. You might try something like this:
$sum = Invoice::selectRaw('currency_symbol, sum(total) as sum')
->join('currencies','invoices.currency_id','=','currencies.id')
->groupBy('currency_id');
return response()->json($sum);

don't want to write query every time while i want to calculation, how can i use variable?

$all_trades = FinalTrade::where('user_id', '=', $user_id)->where('market_id', '=', $market_id)->get();
I'm trying get all entries which has (col: buy_datetime > col: sell_datetime) and (col:buy_rate * quantities).
actually trying to get this in variable.
from $all_trades, how can store whole records of single column in variable?
for example, I want to store col: quantities into $abc varible.
Use pluck to get column from collection
$abc = $all_trades->pluck('quantities');
You can use where raw, this method allows you to write raw sql code for WHERE statement
FinalTrade::whereRaw('buy_datetime > sell_datetime')->get();
Or you can try to use Database Expressions
FinalTrade::where('buy_datetime', '>' DB::raw('sell_datetime'))->get();
For this column buy_rate * quantities you can use selectRaw method
FinalTrade::where('buy_datetime', '>' DB::raw('sell_datetime'))
->selectRaw('buy_rate * quantities as column1')
->get();
`$finalTrades = FinalTrade::get();
$numbers_of_entries = $finalTrades->count();
$finalTrades->transform(function (FinalTrade $finalTrade) use
($numbers_of_entries) {
$finalTrade->result = ($finalTrade->quantities * $finalTrade->buy_rate) /
$numbers_of_entries;
return $finalTrade;
});`

Array match in while-loop

I am developing a search tool for my project,
My desired output is to get the common value from the different tables. eg) SKR0BP100
How to get this value ??
As i am running the program in for-loop and fetching the values from while-loop, now how to use array_intersect() function? Because for array intersect function, minimum 2 arrays are needed, but i get only one array at a time, as it runs on for-loop. So what should i do ?? Please Help me!
$result = array_intersect($arr1, $arr2);
But i have only one $array (ie, $sid[$i] at a time, as it runs in for-loop.
My program
for($i=0;$i<$cc;$i++)
{
$m1="select * from $u$sc where $b[$i]='$a[$i]' ";
$m2=mysql_query($m1);
echo"$m1<br><br>";
while($we=mysql_fetch_array($m2))
{
$sid[$i]=$we['SI'];
echo"$sid[$i]<br><br>";
}
}
Desired Output = SKR0BP100
// How to get this??
Present output
select * from Studentsc where Zone='East'
SKR0BP100
SKR0BP12
select * from Studentsc where Area='Rural'
SKR0BP129
SKR0BP13
SKR0BP100
select * from Studentsc where Class='12'
SKR0BP100
SKR0BP101
So if you want to create query then try this
$where = array();
for($i=0;$i<$cc;$i++)
{
$where[] = $b[$i]."='".$a[$i]."'";
}
$m1="select * from $u$sc where ".implode(" and ",$where); //If you are sure that atleast one value vomes

How to order by count in Doctrine 2?

I'm trying to group my entity by a field (year) and do a count of it.
Code:
public function countYear()
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('b.year, COUNT(b.id)')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->addOrderBy('sclr1', 'DESC')
->addGroupBy('b.year');
$query = $qb->getQuery();
die($query->getSQL());
$result = $query->execute();
//die(print_r($result));
return $result;
}
I can't seem to say COUNT(b.id) AS count as it gives an error, and
I do not know what to use as the addOrderby(???, 'DESC') value?
There are many bugs and workarounds required to achieve order by expressions as of v2.3.0 or below:
The order by clause does not support expressions, but you can add a field with the expression to the select and order by it. So it's worth repeating that Tjorriemorrie's own solution actually works:
$qb->select('b.year, COUNT(b.id) AS mycount')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->orderBy('mycount', 'DESC')
->groupBy('b.year');
Doctrine chokes on equality (e.g. =, LIKE, IS NULL) in the select expression. For those cases the only solution I have found is to use a subselect or self-join:
$qb->select('b, (SELECT count(t.id) FROM \My\Entity\Album AS t '.
'WHERE t.id=b.id AND b.title LIKE :search) AS isTitleMatch')
->from('\My\Entity\Album', 'b')
->where('b.title LIKE :search')
->andWhere('b.description LIKE :search')
->orderBy('isTitleMatch', 'DESC');
To suppress the additional field from the result, you can declare it AS HIDDEN. This way you can use it in the order by without having it in the result.
$qb->select('b.year, COUNT(b.id) AS HIDDEN mycount')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->orderBy('mycount', 'DESC')
->groupBy('b.year');
what is the error you get when using COUNT(b.id) AS count? it might be because count is a reserved word. try COUNT(b.id) AS idCount, or similar.
alternatively, try $qb->addOrderby('COUNT(b.id)', 'DESC');.
what is your database system (mysql, postgresql, ...)?
If you want your Repository method to return an Entity you cannot use ->select(), but you can use ->addSelect() with a hidden select.
$qb = $this->createQueryBuilder('q')
->addSelect('COUNT(q.id) AS HIDDEN counter')
->orderBy('counter');
$result = $qb->getQuery()->getResult();
$result will be an entity class object.
Please try this code for ci 2 + doctrine 2
$where = " ";
$order_by = " ";
$row = $this->doctrine->em->createQuery("select a from company_group\models\Post a "
.$where." ".$order_by."")
->setMaxResults($data['limit'])
->setFirstResult($data['offset'])
->getResult();`

Resources