Using grouby and sum in a query - laravel

I have quite a big query and I'm trying to grab the sum of the orders.price column. With the below code, it returns just 44.00, which is the price for the first row. When I run the raw SQL, it is returning a column with 1,000+ rows of prices in a column called "AGGREGATE". I want to return a single total for all of these prices.
When I remove the groupBy, it works mostly fine. However, the groupby is there as I seem to get duplicate rows back.
$query = Order::leftJoin('customers', 'orders.customer_id', '=', 'customers.customer_id')
->leftJoin('addresses', 'orders.order_id', '=', 'addresses.order_id')
->where('orders.customer_id', '!=', 0);
$query->whereIn('user_id', [3, 5, 10, 15]);
$query->groupBy('orders.order_id');
$sum = $query->sum('orders.price');
I've omitted some of the code here, but the joins are actually necessary.
Here's the generated SQL:
SELECT
sum(`orders`.`price`) AS AGGREGATE
FROM
`orders`
LEFT JOIN `customers` ON `orders`.`customer_id` = `customers`.`customer_id`
LEFT JOIN `addresses` ON `orders`.`order_id` = `addresses`.`order_id`
WHERE
`orders`.`customer_id` IS NOT NULL
AND `orders`.`customer_id` != '0'
AND `orders`.`user_id` IN (3, 5, 10, 15)
GROUP BY
`orders`.`order_id`
ORDER BY
`orders`.`order_id` DESC

You will probably have to replace the JOINs with subqueries:
WHERE EXISTS (
SELECT *
FROM customers
WHERE orders.customer_id=customers.customer_id
AND ...
)
Then you can remove GROUP BY.
If you use relationships:
$query->whereHas('customers', function($query) {
$query->where(...)
})

Related

Convert DB::Select to Query Builder

i has raw query in laravel like this
public function getPopularBook(){
$book = DB::select("
with totalReview as(
SELECT r.book_id , count(r.id)
FROM review r
GROUP BY r.book_id
)
SELECT *
from totalReview x
left JOIN (
SELECT b.*,
case when ((now() >= d.discount_start_date and now() <= d.discount_end_date) or (now() >= d.discount_start_date and d.discount_end_date is null)) then (b.book_price-d.discount_price)
ELSE b.book_price
end as final_price
FROM discount d
right JOIN book b
on d.book_id = b.id
) as y
on x.book_id = y.id
ORDER BY x.count DESC, y.final_price ASC
LIMIT 8"
);
return $book;
}
so when i want to return a paginate, it doesn't work so can i convert this to query build to use paginate
This is a very un-optimized raw query in itself. You are performing too many Join in Subquery just to sort by price
i'm assuming the database table:
books[ id, name, price ]
reviews[ id, book_id ]
discounts[ id, book_id, start_date, end_date, discount_price]
Look how easy it is if you just use Eloquent:
Book::withCount('reviews')->orderBy('reviews_count')->get();
this will give you all the Books order by number of reviews
now with the final price, this can be a bit tricky, let's take a look at a query when we don't consider discount time
Book::withCount('reviews')
->withSum('discounts', 'discount_price') //i'm assuming a book can have many discount at the same time, so i just sum them all
->addSelect(
DB::raw('final_price AS (books.price - discounts_sum_discount_price)')
)
->orderBy('reviews_count', 'asc') // =you can specify ascending or descending
->orderBy('final_price', 'desc') //in laravel chaining multiple orderBy to order multiple column
->get();
I dont even need to use Subquery!! But how do we actually only add the "active" discount?, just need to modify the withSum a bit:
Book::withCount('reviews')
->withSum(
[
'discounts' => function($query) {
$query->where('start_date', '<=', Carbon::now())
->where('end_date', '>=', Carbon::now())
}
],
'discount_price'
)
->addSelect(
DB::raw('final_price AS (books.price - discounts_sum_discount_price)')
)
->orderBy('reviews_count', 'asc') // =you can specify ascending or descending
->orderBy('final_price', 'desc') //in laravel chaining multiple orderBy to order multiple column
->get();
and it is done
What about pagination? just replace the get() method with paginate():
Book::withCount('reviews')
->withSum(['discounts' => function($query) {
$query->where('start_date', '<=', Carbon::now())->where('end_date', '>=', Carbon::now())
}],'discount_price')
->addSelect(DB::raw('final_price AS (books.price - discounts_sum_discount_price)')) //just format to be a bit cleaner, nothing had changed
->orderBy('reviews_count', 'asc')
->orderBy('final_price', 'desc')
->paginate(10); //10 books per page
WARNING: this is written with ELoquent ORM, not QueryBuilder, so you must define your relationship first

Eloquent query distinct sub id

I have these models
I want to make a query that shows me all the products whose stock quantity> 0 and that does not repeat the products.
My query:
$stock_products_limit = Stock::distinct('product_id')->where('quantity', '!=', 0)->get();
This would be much easier using a size chart relating it to stocks ... but for now I don't have it
I need the model to return me, and then do a foreach:
#foreach($stock_products_limit as $stock_product)
#foreach($stock_product->product->product_images as $i=>$product_image)
...
#endforeach
...
#enforeach
In my models I have the hasMany and belongsTo relations made
How could I make the query? I've been trying the distinct, group by ... but nothing works for me. It only removes the ones with quantity 0 and repeats the product ID ...
Example of the query I want:
SELECT DISTINCT(stocks.product_id)
FROM stocks
INNER JOIN products ON stocks.product_id = products.id
WHERE quantity != 0
ORDER BY product_id
LIMIT 10;
Another example query (but LIMIT doesn't work with IN)
SELECT * from products where id in (SELECT DISTINCT(product_id)
FROM stocks
INNER JOIN products ON stocks.product_id = products.id
WHERE quantity != 0
ORDER BY product_id)
Instead of making the Stock model as the starting point, you might want to use the Product model. Then you don't even have to think about using DISTINCT. Let's use whereHas
return Product::whereHas('stocks', function ($query) {
$query->where('quantity', '>', 0);
})
->limit(10)
->get();

Need guidance on how to build a Laravel database query

In Laravel 6.18 I'm trying to figure out how to recreate the following Postgres query.
with data as (
select date_trunc('month', purchase_date) as x_month, date_trunc('year', purchase_date) AS x_year,
sum (retail_value) AS "retail_value_sum"
from coins
where user_email = 'user#email.com' and sold = 0
group by x_month, x_year
order by x_month asc, x_year asc
)
select x_month, x_year, sum (retail_value_sum) over (order by x_month asc, x_year asc rows between unbounded preceding and current row)
from data
I know how to build the main part of the query
$value_of_all_purchases_not_sold = DB::table('coins')
->select(DB::raw('date_trunc(\'month\', purchase_date) AS x_month, date_trunc(\'year\', purchase_date) AS x_year, sum(retail_value) as purchase_price_sum'))
->where('user_email', '=', auth()->user()->email)
->where('sold', '=', 0)
->groupBy('x_month', 'x_year')
->orderBy('x_month', 'asc')
->orderBy('x_year', 'asc')
->get();
but how do you build out the with data as ( and the second select?
I need the data to be cumulative and I'd rather do the calculation in the DB than in PHP.
Laravel doesn't have built-in method(s) for common table expression. You may use a third party package such as this - it has a very good documentation. If you don't want to use an external library, then you need use query builder's select method with bindings such as
$results = DB::select('your-query', ['your', 'bindings']);
return Coin::hydrate($results); // if you want them as collection of Coin instance.

Eloquent methods lumen

I have belongsToMany relationship between items and vehicle.
items can be assigned to multiple vehicles. same vehicle can b assigned to multiple items. so my pivot table item_vehicle have extra column date which will show that when vehicle is assigned to item.
here is my query.
select `items`.`id`, `items`.`name`, `items`.`area` as `total_area`,
`item_vehicle`.`date`, `vehicles`.`name` as `vehicle_name`,
SUM(parcel_vehicle.area) as processed_area
from `parcels`
inner join `item_vehicle` on `item_vehicle`.`p_id` = `items`.`id`
inner join `vehicles` on `item_vehicle`.`t_id` = `vehicles`.`id`
where `item_vehicle`.`date` < '?' and `items`.`processed` = ? and `vehicles`.`name`=?
group by items.id
what will be the eloquent way of doing this
Item::with(['vehicle'=>function($q){$q->wherePivot('date','<','2019/2/12');}])->whereHas('vehicle',function($q){$q->where('vehicles.id','2');})->where('processed',1)->where('id',4)
->get();
my concerns is it should run only one query
$parcels = Parcel::join('item_vehicle', 'item_vehicle.pid', '=' ,'items.id')
->join('vehicles', 'vehicles.id', '=' ,'item_vehicle.t_id')
->where('item_vehicle.date', '<', $date)
->where('items.processed', $processed)
->where('vehicles.name', $vehicleName)
->select(
'items.id',
'items.name',
\DB::raw('items.area as total_area'),
'item_vehicle.date',
\DB::raw('vehicles.name as vehicle_name'),
\DB::raw('SUM(parcel_vehicle.area) as processed_area')
)
->groupBy('items.id')
->get();
However, you have non-aggregated columns in select and you are doing group by. To make this work you might need to disable mysql's only_full_group_by mode

Laravel Eloquent - Eager Loading Query is Being Restricted by limit()

I have the following query:
MyTable::where('my_column', '=', 25)->with('myOtherTable')
->orderBy('id', DESC)->limit(5);
I would like the above to bring me results analogoous to the following raw SQL query:
SELECT *
FROM myTable AS ABB1
LEFT JOIN myOtherTable AS ABB2 ON ABB1.id = ABB2.myTable_id
WHERE my_column = 25
ORDER BY myTable.id DESC
LIMIT 5;
The above will find everything in myTable along with corresponding info from myOtherTable and then limit the results to 5 rows.
When I run the eloquent statement above, two SQL queries are processed. The first looks something like:
SELECT *
FROM myTable
WHERE my_column = 25
ORDER BY id DESC;
If this query returns say 7 result items, but I pass in a smaller number into the limit() function (ie. limit(5)), then the corresponding eager loading query will look like:
SELECT *
FROM myOtherTable
WHERE id IN(1, 2, 3, 4, 5);
The eager loading query is itself limited to 5 items. There should be no limit here. The number of items in the IN conditional above should be 7 (or whatever the count returned from the first query is). The limit should only be applied after the second query runs.
How would I do this with Eloquent?
You can use eloquent's join.
MyTable::join('myOtherTable', 'column_id', '=', 'id')
->where('my_column', '=', 25)
->with('myOtherTable')
->orderBy('id', DESC)
->limit(5);
The with is only if you want to eager load the relation on MyTable.

Resources