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

$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;
});`

Related

Arithmetic operations in select with 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

What is the equivalent query of laravel on this?

This is the native sql:
$sql = "Select count(name) from users Where email = 't#t.com' and user_id = 10";
I have this laravel code:
$checker = Customer::whereEmailAndUserId("t#t.com",10)->count("name");
Is this a correct way to do it in laravel?
You have to use where helper function and pass an array of checks. For example in your code it will be:
$checker = Customer::where([
['email', '=', 't#t.com'],
['user_id' '=', '10']
])->count();
Note: Please use the appropriate column name as it in table.
Assuming Customer model represents table users, you'll get query with eloquent like this:
Customer::where('email', 't#t.com')->where('user_id', 10)->select(\DB::raw('count(name)'))->get();
The option you are trying is incorrect
here is the right option
$users = \App\Customer::where('email','t#t.com')
->where('user_id',10)
->count()
Explanation of above code
App\Customer is the Model class and I am trying to read records where email = 't#t.com you can use various comparison operators like <,> and so on and you can also use the same function to for string pattern matching also
Eg.
$users = \App\Customer::where('email','%t.com')
->where('user_id',10)
->count()
You can use the same where function for Null Value test also
Eg.
$users = \App\Customer::where('email','=', null)
->where('user_id',10)
->count()
The above where clause will be converted to is null test of the SQL
You can read more here

Skip and take all?

In eloquent, how can I skip 10 rows and then get the rest of the table?
User::skip(10)->all();
The above does not work, but it gives you an idea what I am looking for.
Try this:
$count = User::count();
$skip = 10;
User::skip($skip)->take($count - $skip)->get();
With one query:
User::skip($skip)->take(18446744073709551615)->get();
It's ugly, but it's an example from official MySQL manual:
To retrieve all rows from a certain offset up to the end of the result
set, you can use some large number for the second parameter. This
statement retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615;
try something like this it work for sure..
$temp = User::count();
$count = $temp - 10;
$data = User::take($count)->skip(10)->get();
Laravel 5 returns Eloquent result as Collection.
So you can use collenction function slice();
$users = User::get();
$slicedUsers = $users->slice(10);

Using whereIn method to return multiple results for the same array value but at different index

$pidArray contains product ID's, some of those product ID's can be the same. I.E: 34 34 56 77 99 34. As is, it appears the whereIn method does not return results for a productId it has already found in $pidArray, even if it has a different index.
$productDataForOrder = Product::whereIn('id', $pidArray)->get(['id','price']);
$totalAmount = $productDataForOrder->sum('price');
$productDataForOrder now contains product data, but only for unique ProductID's in $pidarray. So when sum function is run, the sum is wrong as it does not take into account the price for multiple instances of the same productID.
The following code also does not return objects for every product ID in the array which are the same. So if $pidArray contains three identical product ID's, the query will only return a collection with one object, instead of three.
$query = Product::select();
foreach ($pidArray as $id)
{
$query->orWhere('id', '=', $id);
}
$productDataForOrder = $query->get(['id','price']);
$totalAmount = $productDataForOrder->sum('price');
You're not going to be able to get duplicate data the way that you're trying. SQL is returning the rows that match your where clause. It is not going to return duplicate rows just because your where clause has duplicate ids.
It may help to think of it this way:
select * from products where id in (1, 1)
is the same as
select * from products where (id = 1) or (id = 1)
There is only one record in the table that satisfies the condition, so that is all you're going to get.
You're going to have to do some extra processing in PHP to get your price. You can do something like:
// First, get the prices. Then, loop over the ids and total up the
// prices for each id.
// lists returns a Collection of key => value pairs.
// First parameter (price) is the value.
// Second parameter (id) is the key.
$prices = Product::whereIn('id', $pidArray)->lists('price', 'id');
// I used array_walk, but you could use a plain foreach instead.
// Or, if $pidArray is actually a Collection, you could use
// $pidArray->each(function ...)
$total = 0;
array_walk($pidArray, function($value) use (&$total, $prices) {
$total += $prices->get($value, 0);
});
echo $total;
The whereIn method only limits the results to the values in the given array. From the docs:
The whereIn method verifies that a given column's value is contained within the given array
Id make a query variable and loop through the array adding to the query variable in each pass. Something like this:
$query = Product::select();
foreach ($pidArray as $id)
{
$query->where('id', '=', $id);
}
$query->get(['id','price']);
Here is a code that would work for your use case expanding on #patricus
You first fetch an array of key as id and value as price from the products table
$prices = Product::whereIn('id', $pidArray)->lists('price', 'id');
$totalPrice = collect([$pidArray])->reduce(function($result, $id) use ($prices) {
return $result += $prices[$id];
}, 0);

how to make query with substr in eloquent (laravel 4)?

I have this query:
select substr(id,1,4) as id
from meteo.a2012
group by substr(id,1,4)
I just want to take first 4 numbers to my id row, but I'm trying to do in eloquent, how I do?
Thanks.
You need to use raw expressions so you can use special functions like that.
Model::select(DB::raw('substr(id, 1, 4) as id'))->groupBy(DB::raw('substr(id, 1, 4)'))->get();
Where Model is your Eloquent model you want to run the query on.
G'day
I was able to do it like this in Laravel
$data = DataModel::selectRaw("SUBSTRING_INDEX(EMAIL_COLUMN, '#', 1) as 'alias'")->get();
As a result, I get the alias name (address) from the mail address#domain.net
$ids = Model::get(['id']);
foreach ($ids as $str)
{
$str->id =substr($str->id,1,4);
}
return $ids;

Resources