How to merge count and sum queries in one query in Eloquent - laravel

I have problem with queries in my Controller. I want to count rows and sum by column in one query.
Relations view
So far, I created two queries:
Query to count rows
$paymentsCount = Payments::where('pay_status', 'like', "%{$payStatus}%")->count();
Query to sum
$paymentsValue = Payments::where('pay_status', 'like', "%{$payStatus}%")->sum('brutto');
I have no Idea, how to make on query instead this two queries.
I will be grateful for any help.

The query builder allows you to customize your SELECT clause with the select() method.
Use it to add COUNT() and SUM() in addition of the other columns:
$payments = Payments::select('*', 'COUNT(*) AS count', 'SUM(brutto) AS sum')
->where('pay_status', 'LIKE', "%{$payStatus}%")
->get();

Related

Eloquent: Order by sum of two columns

My working SQL query is as follows:
SELECT post_id
FROM news_tags
ORDER BY (link_clicks+views) DESC
What I've tried so far in eloquent is like this:
$newsTagSaved = NewsTag::
orderBy(DB::raw("`views` + `link_clicks`"), 'desc')
->paginate(12)
->pluck('post_id');
Newstag table has many columns and views and link_clicks are two of them. Now, I'm trying to retrieve the post_id order by desc of sum of views and link_click.
How can I do it in Laravel eloquent?
Thank you!
Do something like this:
$newsTagSaved = NewsTag::select(DB::raw('views + link_clicks as score'))
->orderBy('score', 'desc')
->get();
dd($newsTagSaved);
This will return just score value. If you want to return other fields, simply add them to select. As an example:
$newsTagSaved = NewsTag::select(
DB::raw('views + link_clicks as score'),
'title',
'created_at'
)
->orderBy('score', 'desc')
->get();
dd($newsTagSaved);

Laravel join two tables with where that compares two date time columns

I have two tables that I want to run joint query on using the value of two date time columns, I have products table and sync_status tables, I want to return all products with updated_at date time greater than synced_at date time.
DB::table('products')
->join('sync_statuses', function ($join) {
$join->on('products.product_number', '=', 'sync_statuses.product_number')
->where('products.updated_at', '>', 'sync_statuses.synced_at')
->whereNull('products.deleted_at');
})
->select('products.product_number');
This SQL represents what I am trying to achieve using Eloquent:
SELECT products.product_number
FROM products
JOIN push_statuses
ON products.product_number = statuses.product_number
AND (
statuses.synced_at IS NULL
OR products.updated_at > statuses.synced_at
)
You have to use on() instead of where() to compare columns:
->on('products.updated_at', '>', 'sync_statuses.synced_at')
This worked for me:
DB::table('products')
->join('statuses', function ($join) {
$join->on('products.product_number', '=', 'statuses.product_number')
->where(DB::raw('products.updated_at'), '>=', DB::raw('statuses.synced_at'))
->whereNull('products.deleted_at');
})->select('products.product_number');
I needed to use DB::raw('products.updated_at') to reference each date time column in the where() clause.

Laravel join with limit

I have the following working for laravel paginate
$query = DB::table('clients')
->leftJoin('radusergroup', 'clients.username', '=', 'radusergroup.username')
->leftJoin('recharge', 'clients.username', '=', 'recharge.soldto');
I want to join some values from two tables radusergroup and recharge. radusergroup always return one row as it has only one row stored whereas recharge table return multiple rows. I want only one row returned from recharge table which is latest entry.
Right now its return all the possible rows from recharge table and showing it on paginated view.
This is Laravel Official documentation
DB::table('clinets')
->leftJoin('radusergroup', 'clients.username', '=', 'radusergroup.username')
->leftJoin('recharge', function ($leftJoin) {
$leftJoin->on('clients.username', '=', 'recharge.soldto')
->where('recharge.create_date', '=', DB::raw("(select max(`create_date`) from recharge)"));
})
->get();
this is the case if you have create_date column in your table, if you haven't got it I strongly recommend to create that column.

Eloquent count() always returns 1

I have the following query:
Item::select(['items.id', 'inventory.quantity'])
->leftJoin('inventory', 'items.id', '=', 'inventory.item_id')
->groupBy('items.id')
->count();
The count() method always returns 1 despite there being 20 rows to the results that are returned. Why might this be?
Here is the raw query from DB::getQueryLog():
select
count(*) as aggregate
from
`items`
left join
`inventory` ON `items`.`id` = `inventory`.`item_id`
group by `items`.`id`
If you only need the correct number of rows from a grouped result, and you don't care that much about the performance then you can call get() first and then call count() on that.
$count = Item::select(['items.id', 'inventory.quantity'])
->leftJoin('inventory', 'items.id', '=', 'inventory.item_id')
->groupBy('items.id')
->get()
->count();
Yes, count returns only 1 row, always.
You would probably want:
Item::select(['items.id as id', 'inventory.quantity as quantity'])
->leftJoin('inventory', 'items.id', '=', 'inventory.item_id')
->groupBy('items.id')
->lists('quantity', 'id');
this will return an array with id as keys, and quantity as values. Otherwise use get, but never count if you want grouped results.

subquery with distinct clause in query builder/laravel

SELECT * FROM `movie_list`
WHERE `movie_id` IN
(SELECT DISTINCT movie_id FROM `movie_genre` where genre_id in (12,18,53))
AND rated IN
('Not Rated','N/A')
How can i convert the above to a query builder syntax:
$movies = DB::table('movie_list')
->whereIn('movie_id',function($query){
$query->select.....
})->get();
I have the inner one: it goes like this:
DB::table('movie_genre')
->whereIn('genre_id', array(12,18,53))
->distinct()
->get(array('movie_id'));
How do i use this result with the rest of my query?
You could do this alot smoother with Eloquent Models, but assuming you don't have your models setup, this should do the trick (untested)
$ids = DB::table('movie_genre')
->whereIn('genre_id', [12,18,33])
->distinct()
->get(['movie_id'])
->toArray();
$movies = DB::table('movie_list')
->whereIn('movie_id', array_values($ids))
->get();

Resources