kohana order group by and count - orm

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...

Related

Convert sql join query to laravel

SELECT school_courses.*, schools.school_name, schools.country, schools.city FROM
school_courses JOIN schools ON school_courses.school_id = schools.id
Hello there,
I want to convert the above SQL query to laravel.
And also I want to learn joins in laravel query please share any easy step by step tutorial link if you have one.
This is Query Builder way of doing it.
$result = DB::table('school_courses')
->join('schools','schools.id','=','school_courses.school_id')
->select('school_courses.*','schools.school_name', 'schools.country', 'schools.city')
->get();
Refer this link https://laravel.com/docs/8.x/queries#joins
My suggestion is to use better Eloquent: Relationships
Relationships
Your converted query is given below
use Illuminate\Support\Facades\DB;
$users = DB::table('school_courses')
->join('schools', 'us schools ers.id', '=', 'contacts.user_id')
->select('school_courses.*','schools.school_name', 'schools.country', 'schools.city')
->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

Laravel eloquent query to get the result groupBy(month)

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();

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();