Aggregate function in laravel 5.4 with joining - laravel

I have two tables :
users table
{id, name}
payments table
{id, user_id, payment}
Here I want to join two tables and want to use SUM(payment) function group by id.
please give me a solution.

You can do join like this way:
$payments = DB::table('users')->join('payments','users.id','=','payments.user_id')->groupBy('users.id')->sum('payment');
//use DB to in you controller

You can use a queryBuilder for make de custom query.

Related

How to Syntax OrderBy whit value in eloquent

I need to add a by order with value in eloquent, how can I do it?
example
Order By
c.id = 23 DESC
enter image description here
Is this a joined table if yes show model and controller?
if it not joined table then try this:
->orderBy('c.id','DESC'), or ->orderByCId('DESC') or ->orderByDesc('c.id')

how to use where in a query with Foreign key in laravel?

I'm trying to make a query to get my data base on Dispenser's state_id. so here's my Database :
Dispenser Table: id, state_id, town_id, name.
Marketer Table: id, state_id, town_id, fname, lname.
DistributorDispenser Table: distributor_id['foreign key to distributor table', which it doesn't matter for this example], dispenser_id['foreign key to dispenser id'].
Consider below query which i was using for my spa which it's vue.js & laravel, now i want to change this query to check dispenser state_id then get detail base on user state_id.
I mean when we use relation to get some data base on relationship, like ->detail(function name in Model), i want my query to execute where query with DistributorDispenser->dispenser->state_id for my auth()->user()->detail()->state_id.
return SellerCentralResources::collection(DistributorDispenser::where('state_id', auth()->user()->detail->state_id)
->latest()
->get());
You need to use
https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence
DistributorDispenser::query()
->whereHas('dispenser',function($q){
$q->where('state_id', auth()->user()->detail->state_id);
})
->latest()
->get();

Laravel Eloquent select function cause empty relation

Following is my query
$user = User::select(['uuid','name','about'])->with(['education','work'])->first();
this returns empty data for relationship education and work,
but if I remove select function from query I am getting data in relationship and it also returns all columns of user table which I don't want.
how can solve this problem
The problem is that relationships (with(...)) execute an additional query to get the related results. Let's say you have one to many relationship where users have many works. User::with('work')->find(1) will then execute these 2 queries:
select user where id = 1 and select works where user_id = 1.
So basically in order to be able to execute the second query (fetch relationship data) you need to include id (or whichever column you're referencing) in you select statement.
Fix:
$user = User::select(['uuid','name','about', 'id'])->with(['education','work'])->first();
Same principle in different forms applies to all relationships. For example in the inverse of hasMany which is belongsTo you would need to select the foreign key (for example user_id).

Newest items and GROUP By with Eloquent

I have the following prices-table:
shop_id (int)
product_id (int)
price (float)
created (DateTime)
Every hour a cronjob checks the shops and inserts new entries (current prices) into these price-table.
Now I want to display the newest price for a product. I have to GROUP BY the shop_id because I only want one price per shop but I only want the newest entry (created).
Can I solve this with Eloquent Query-Builder or do I have to use raw SQL? Is it possible to pass the result of a raw SQL-query into a model if the columns are the same?
You can try it as:
Price::select('*', DB::raw('MAX(created_at) as max_created_at'))
->groupBy('shop_id')
->get()
Assuming model name is Price
Eloquent (purist) approach:
Price::orderBy('created', 'desc')->groupBy('shop_id')
->get('shop_id', 'price');
References:
https://laravel.com/api/5.3/Illuminate/Database/Query/Builder.html#method_orderBy
https://laravel.com/api/5.3/Illuminate/Database/Query/Builder.html#method_groupBy
https://laravel.com/api/5.3/Illuminate/Database/Query/Builder.html#method_get
*untested though
Q: Is it possible to pass the result of a raw SQL-query into a model if the columns are the same?
A: you could pass it to Model's contructor - but it might need model's field to be fillable - or hydrate a model. Alternatively, just access it like an keyed-array, ie. $something[0]['price'] <-- assuming an array of prices with price column.
I solved the problem without QueryBuilder. Instead I use a raw SQL-statement and generating the models with the hydrateRaw()-function of the Model-class.
$prices = Price::hydrateRaw( 'SELECT p.*
FROM prices p
INNER JOIN (
SELECT shop_id, max(created_at) AS max_ca
FROM prices p1
GROUP BY shop_id
) m ON p.shop_id = m.shop_id AND p.created_at = m.max_ca');

Eloquent Subquery

I have a many to many relationship between a student table and a apparatus table (A student performs on many apparatuses and an apparatus has many students). I have a student_results table that has a composite primary key (student_id and apparatus_id) and a 3rd field called results).
I have written a query to find all the apparatuses that a student DOES NOT have a result. The example I give is for student with id = 121.
The sub-query is.
SELECT apparatus_id, strapparatus_name FROM apparatuss
WHERE apparatus_id <> ALL(SELECT apparatus_id FROM student_results
WHERE student_id =' . 121 . ')';
I would like to write this using Eloquent (Laravel 4.1).
Any help greatly appreciated.
Assuming that you already have your Eloquent models Apparatus and StudentResult set, this is a way:
Apparatus::whereNotIn(
'apparatus_id',
StudentResult::where('student_id', 121)->lists('apparatus_id')
)->get('apparatus_id', 'strapparatus_name');
Or, if you don't have a model for your student_results table, you can just:
Apparatus::whereNotIn(
'apparatus_id',
DB::table('student_results')->where('student_id', 121)->lists('apparatus_id');
)->get(array('apparatus_id', 'strapparatus_name'));

Resources