Laravel eloquent query to get the result groupBy(month) - sql

How to get a result with groupBy(month('start_date'))
So far I have
$this->data['earnings'] = DB::table('documents')
->leftJoin('users','users.id', '=', 'documents.users_id')
->leftJoin('users_editors','users_editors.user_id','=','users_id')
->groupBy(month ('start_date'), 'DESC')
->sum('amount')
->get();
I am trying to get earnings for all the editors groupBy month which will take month from start_date to have a groupBy on.
Thanks

In order to use (My)SQL functions you need raw statements, that are not processed and bound by PDO or, in this case, treated as a field name:
->groupBy(DB::raw('month(start_date)'))
In order to make it work as you expect:
->selectRaw('month(start_date) as month, sum(amount) as sum')
->groupBy(DB::raw('month desc'))
// or:
->groupBy('month')
->orderBy('month', 'desc')
->get();

Related

Laravel Convert SQL to Eloquent : order by a sum()

I'm new to Eloquent and Laravel. I tried multiple syntaxes but I can't find a way to make it work. Here is the query I would like to convert :
SELECT category, SUM(amount) AS `total_cat` FROM expenses GROUP BY category ORDER BY `total_cat` DESC
And here's my Model for the "expenses" table :
class Expense extends Model
{
use HasFactory;
protected $fillable = ['date', 'title', 'amount', 'category'];
}
The idea here is to get the sum of expenses for each category (the alias is not necessary). The query is working just fine in pure PHP. Thanks for your help :)
This may be the solution, I haven't test but it seem fits the theory within the eloquent functions
Expense::select([
'category',
DB::raw('SUM(category) AS category_sum')
])
->groupBy('category')
->orderBy('total_cat', 'desc')
->get()
Here's what worked for my initial problem:
Expense::select([
'category',
DB::raw('SUM(amount) AS total_cat') ])
->groupBy('category')
->orderBy('total_cat', 'desc')
->get();

Laravel - Nested select (Eloquent)

I have a scores table that I have to group by the attempt_number and take the sum of scores
I want to nest this query using Eloquent and SQL raw and take the Max score from the attempts and order it according to score. I need the final result as a leaderboard.
$usersByScore = Attempt::where('game_id',$id)
->select('user_id','attempt_no','game_id',DB::raw('SUM(score) as total_score'))
->groupBy('attempt_no')
->orderBy('total_score', 'DESC')
->get()
this gives me the leaderboard but it has all attempts from the user. I need just the max score attempt for each user ordered by the score in descending order.
use distinct() method for this: i hope it will work.
$usersByScore = Attempt::where('game_id',$id)
->select('user_id','attempt_no','game_id',DB::raw('SUM(score) as total_score'))
->groupBy('attempt_no')
->orderBy('total_score', 'DESC')
->distict()
->get()
Got the solution - Implemented the from method to nest the query
$usersByScore = Attempt::with('user')
->select(DB::raw('MAX(tscore) as total_score, user_id,attempt_no'))
->from(DB::raw('(SELECT user_id,attempt_no,SUM(score) as tscore FROM
attempts WHERE game_id = '.$id.' GROUP By attempt_no,user_id) AS T'))
->groupBy('user_id')
->get();

Can't get all data from table with laravel raw query and group_concat

Although I have 3 different teacher reports on the table and all the dates are same, i can only get last teacher's report
$report = DB::table('users')
->join('classreports', 'classreports.teacherId', '=', 'users.id')
->where('classreports.classId', '=', Input::get('classId'))
->where('classreports.reportDate', '=', $reportDate)
->groupBy('classreports.reportDate')
->select('users.fullName', 'classreports.reportDate', DB::raw('group_concat(classreports.report) as report'))
->get();
return json_encode($report);
How can i get all teacher's report?
Thanks.
You can try this
->groupBy('classreports.teacherId','classreports.reportDate')
Can group by teacherID and reportDate

kohana order group by and count

I have orm query like tthis:
$userCountries = ORM::factory('User')
->select(array(DB::expr('countries.code, COUNT("countries.id") as total')))
->join('countries')
->on('user.country_id', '=', 'countries.id')
->group_by('country.name')
->order_by('total', 'DESC')
->find_all();
What i want is country code with total users quantity from country.
I do not know what is wrong here. I spent 3 hours on it with no success.
What is wrong with this query?
Your SELECT Params is wrong
->select('countries.code', array(DB::expr('COUNT("countries.id")', 'total')))
I think the Group by should be
->group_by('countries.name') instead of ->group_by('country.name')
So Your Total Query will look like
$userCountries = ORM::factory('User')
->select('countries.code', array(DB::expr('COUNT("countries.id")', 'total')))
->join('countries')
->on('user.country_id', '=', 'countries.id')
->group_by('countries.name')
->order_by('total', 'DESC')
->find_all();`
Check this out...

OrderBy count appearing in the wrong order in Eloquent Query Builder (Laravel 4)

I have the following query:
public static function artists_most_popular() {
$artists_most_popular = DB::table('artists')
->join('fanartists', 'artists.id', '=', 'fanartists.artist_id')
->orderBy(DB::raw('count(*)', 'DESC'))
->groupBy('artists.id')
->take(50)
->get();
return $artists_most_popular;
}
As you can see from the query, I would like the data to appear in descending order by count of the times the artist_id appears in the fanartists table. However, when I use "foreach" and output this data, it appears in ascending order. Any ideas for why this is happening? I used the following query in SQL Pro, and it works as it should:
select *, COUNT(*)
from artists
join fanartists on artists.id = fanartists.artist_id
group by artists.id
order by (COUNT(*)) desc
I have changed the query little bit. Hopefully this will work.
$artists_most_popular = DB::table('artists')
->join('fanartists', 'artists.id', '=', 'fanartists.artist_id')
->select(DB::raw('artists.*, fanartists.*, COUNT(*) AS total_artists'))
->orderBy('total_artists', 'DESC'))
->groupBy('artists.id')
->take(50)
->get();
Also if you want your Artists collection to be returned (this pretends your Artists Model is called Artists), and to further enhance Anam's response, you could do something like:
$artists_most_popular = Artists::join('fanartists', 'artists.id', '=', 'fanartists.artist_id')
->select(DB::raw('artists.*, fanartists.*, COUNT(*) AS total_artists'))
->orderBy('total_artists', 'DESC'))
->groupBy('artists.id')
->take(50)
->get();