Laravel Query builder - ->offset() doesnt want to work with computed column - laravel

I'm using query builder and have this query which works
$athletes = DB::table('athletes')
->select("athletes.first_name", "athletes.last_name",
DB::raw('MAX(performance) AS personal_best')
)
->leftJoin("performances", "athletes.id", "=", "performances.athlete_id")
->groupBy("athletes.id", "athletes.first_name", "athletes.last_name")
->orderBy("personal_best", "DESC")
->get();
but now I need to do pagination so I added
->offset(5)
->limit(10)
and now it is giving me an error:
Invalid column name 'personal_best'
I was trying to find a solution to this but so far with no success. If anybody has any idea it would be very welcomed!

Related

Add extra column to laravel select query

It may sound as a duplicate question. Please I have not found a working solution.I want to add additional field to my query in laravel but I am getting error. This is the php implementation
select id, "extra_column as type" from cases
have tried
DB::table('cases')
->select(['id'])
->selectSub(function($query){
$query->selectRaw('extra_column');
},'type')
->get();
but I keep getting error
You need to use like this:
DB::table('cases')
->select(['id', 'extra_column as type'])
->get();
Please try addSelect('extra_column as type').
DB::table('cases')
->select(['id'])
->addSelect(`<additional column>`) // We can able to use variable as well $value = 'extra_column as type';
->get();
I later found out the solution. the extra_column was missing a double quote
DB::table('cases')
->select(['id'])
->selectSub(function($query){
$query->selectRaw('"extra_column"');
},'type')
->get();
You can find that scenario in Laravel docs like so,
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
OR you can do something like this also:
DB::table('users')->select('name')
->addSelect('email as user_email');
and in case this triggers an issue as you told, please make sure that this column exists in your database.

GroupBy with multiple Join, Laravel

I want to groupBy teacher_id and by day_of_the_week, with this current code I don't get any error, but I get no join at the end. If I use only teacher_id and day_of_the_week in groupBy I get errors.
$schedule = Schedule::select(
'schedules.teacher_id',
'schedules.day_of_the_week',
'schedules.semester',
'schedules.hour_start',
'schedules.hour_end',
'teachers.name as teacher_name',
'rooms.name as room_name',
'groups.name as group_name',
'courses.name as course_name',
)
->leftJoin('teachers','teachers.id','schedules.teacher_id')
->leftJoin('rooms','rooms.id','schedules.room_id')
->leftJoin('groups','groups.id','schedules.group_id')
->leftJoin('courses','courses.id','schedules.course_id')
->groupBy(['schedules.teacher_id',
'schedules.day_of_the_week',
'schedules.semester',
'schedules.hour_start',
'schedules.hour_end',
'teacher_name',
'room_name',
'group_name',
'course_name'])
->get();
//Second version
Schedule::select('schedules.*')
->with(['teachers' => function($query){
return $query->groupBy('name');
},'groups', 'courses','rooms'])
->get();
The current response.
Update
I find a way to do this with the first code from above and but on a deeper level on day_of_the_week, I am not sure how..
$schedule = $schedule->groupBy('teacher_name'); // on collection
I have a solution that I tried and it works. GroupBy on different table fields you can do only by Change DB mode strict to false. Goto
ProjectRootDir/Config/database.php file goto Mysql and change the strict value to FALSE the default value is TRUE.
Hope your problem will solve.
Thanks

Laravel Sorting Data with Relationship and Pagination

I need sorting the Records data according to Relationship.
I am trying below Query.
$data = Lead::with('bdm', 'status_code', 'bdm.bdm')->get()->sortByDesc('bdm.bdm.name');
It works fine but I need data with pagination which is giving by Laravel 5 by default.
So If I am trying with below query . It is giving error.
$data = Lead::with('bdm', 'status_code', 'bdm.bdm')->pagination(20)->sortByDesc('bdm.bdm.name');
I am trying an other way to do the same task. It works fine but it is not sorting the records.
$data = Lead::with(['bdm','status_code', 'bdm.bdm' => function ($query) {
$query->orderBy('name', 'desc');
}])->paginate(20);
So kindly can anyone give me solution how to adjust this query.
Any Help will be appreciated.
Thanks
You should be using a join statement to do that.
If I were to assume your column names it should look something like this:
$data = Lead::with(['status_code', 'bdm.bdm'])
->join('bdms', 'bdms.id', '=', 'leads.bdm_id')
->orderBy('bdms.name', 'desc')
->paginate(20);
And the first bdm parameter in your query is redundant. It will be handled during bdm.bdm anyway.

Laravel Query Result Issue: query is returning empty array even there is data exist into database

I am working on laravel 5.4. I am trying to get data from database using below query:
$obj = \Illuminate\Support\Facades\DB::table('A')
->join('B', 'A.Intake', '=', 'B.Id')
->join('C', 'B.StreamId', '=', 'C.StreamId')
->select(\Illuminate\Support\Facades\DB::raw('DISTINCT(C.StreamId) As StreamId'))
->where('A.YearId', $yearId);
$streamIds = $obj->get()->toArray();
The above query is returning empty results. I have also debug the query generated by laravel. Below is the raw query generating by laravel on the basis of above conditions:
select DISTINCT(C.StreamId) As StreamId from A
inner join B on A.Intake = B.CentreStreamId
inner join C on B.StreamId = C.StreamId
where A.YearId = '12'
When I run the above raw query directly in my database, then it returns me some records. But when I try to get records in laravel then it returns me empty results.
I am not able to get the issue with the above query. Can someone please tell me why it is returning empty results set? If there is any issue with above query builder syntax then please correct my query.
Thanks in Advance.

Pagination creates an error

Im trying to paginate a search to bring back pages of 18 items. Previously i had this code working code:
$productsQuery = Product::where('approved', '=', 1)->leftJoin('reviews', 'reviews.products_id', '=', 'products.id')->select('products.*', DB::raw('AVG(ratings) as ratings_average' ))->groupBy('id')->orderBy('ratings_average', 'DESC');
I add on paginate to this as shown in the docs
$productsQuery = Product::where('approved', '=', 1)->leftJoin('reviews', 'reviews.products_id', '=', 'products.id')->select('products.*', DB::raw('AVG(ratings) as ratings_average' ))->groupBy('id')->orderBy('ratings_average', 'DESC')->paginate(18);
And get an error
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in group statement is ambiguous
Any ideas on how to paginate the statement?
It's not neccesarily the pagination which is causing the issue, the error is caused by your group by.
You should place the table name / alias name prior to the id EG:
$productsQuery = Product::where('approved', '=', 1)->leftJoin('reviews', 'reviews.products_id', '=', 'products.id')->select('products.*', DB::raw('AVG(ratings) as ratings_average' ))->groupBy('product.id OR reviews.id')->orderBy('ratings_average', 'DESC');
Please see the ammended statement above, note that copy pasting it won't work, you'll see to change that groupby argument.
You should also visit the docs on Eloquent, you have approached this in a way where you're fighting laravel. I would suggest getting a tighter grip on the ORM used.
Good luck!
The error is pretty self explanatory here:
Column 'id' in group statement is ambiguous
so you need to make
`groupBy('id')`
more explicit, by telling which id (from which table, as each table used in your query features id column) you want to be used for grouping.

Resources