How to add paginate function to join and groupBy query? - mysql

I am trying to achieve pagination after joining and grouping the query.
I have already tried other ideas but can't make pagination object appear, instead it will only show as a normal collection.
$this->join('products', 'products.id', '=', 'stocks.product_id')->get()->groupBy('title');
I tried $this->join('products', 'products.id', '=', 'stocks.product_id')->get()->groupBy('title')->paginate(15); but it doesn't work. Where should i add paginate() function or do i need to do something other than that? Please let me know if i should explain more.

When you call get() method, the paginate() method won't work anymore. So just remove the get() method like this : $this->join('products', 'products.id', '=', 'stocks.product_id')->groupBy('title')->paginate(15);

From what I have found so far, there seems to be an issue in pagination with groupBy() in Laravel. So, in order to achieve this, it is recommended that you query the database and create a paginator manually.

You should try this:
$this->join('products', 'products.id', '=', 'stocks.product_id')->groupBy('title')->paginate(15);

Related

DB Laravel Query, get a datagroup in join for each data

I am using Laravel, I would like to know how I can obtain this result using DB::
[{'id':1,'name':'A',pictures:[{'property_id':1,'filename':'A01'},{'property_id':1,'filename':'A02'},{'property_id':1,'filename':'A03'}]}]
Right now I'm using eloquent relationships and it works fine but it's slow so I want to do it directly with DB::
PROPERTIES
PICTURES
Is it necesary to make it exactly in that format?
To just get all data you want as one object try something like:
DB::table('properties')
->join('pictures', 'property_id',
'=', 'properties.id')
->select('*')
->get()->toArray();

laravel eloquent join where clause with sub query to use column name comparision not working

I am having issues with laravel eloquent join to compare date in where clause using sub query. below query gives me error unknown column policy_periods.statecode i am using this column in where clause of the join subquery for example App\Elrd::where("state_code",'=',DB::raw(policy_periods.statecode))->where('date',"<=",$mod_rating_eff_date)->max('date')
can you please give me an idea if any solution possible ?
i have already tried whereRaw, whereColumn but none of them is working.
DB::table('policy_periods')
->join('payrolls','payrolls.policy_period_id', '=', 'policy_periods.id')
->leftjoin('elrds', function($join) use($mod_rating_eff_date)
{
$join->on('elrds.state_code', '=', 'policy_periods.statecode');
$join->on('elrds.class_code', '=', 'payrolls.code');
$join->where('elrds.date',App\Elrd::where("state_code",'=',DB::raw(`policy_periods`.`statecode`))->where('date',"<=",$mod_rating_eff_date)->max('date'));
})
->select('payrolls.*','payrolls.elr as payrollelr','policy_periods.id as pid','policy_periods.policy_no',DB::raw('CONCAT(eff_date, "-", exp_date) as dateGroup'),'policy_periods.eff_date','policy_periods.exp_date','policy_periods.statecode as ratingeffPolicyYear','policy_periods.statecode','elrds.class_code','elrds.year','elrds.date','elrds.elr','elrds.dratio')
->where('policy_periods.mod_id',$id)
->get();
When I encounter such issue, the first thing I usually do is to determine if the generated query is what I wanted.
You should log your queries so that you can ensure it.
To do that, a possible solution is to add a log in your AppServiceProvider (in function boot):
DB::listen(function ($query) {
Log::debug('query',[
$query->sql,
$query->bindings,
$query->time
]);
});
That being said, where do these backticks come from?
DB::raw(`policy_periods`.`statecode`)
You could replace it with DB::raw('policy_periods.statecode')
Please tell me if it fixes your issue, or provide the generated SQL query if the problem is not fixed.

MySQL to Eloquent query

I've been having some issues with a query. I'm trying to get the most recent record for each 'category' from a table, but I can't figure out how to write the query in Laravel.
I got the query working in MySQL, but no real luck in translating it.
The MySQL query looks like this:
SELECT *
FROM messages
WHERE id IN (
SELECT MAX(id)
FROM messages
GROUP BY conversation_id
);
I was trying something like this in Laravel, but it doesn't seem to work:
return self::where(function($query){
$query->select(max(['id']))
->from('messages')
->groupBy('conversation_id');
})
->get();
(Posted on behalf of the OP).
Thanks to AlexM's comments I figured it out.
return self::whereIn('id', function($query){
$query->select(max(['id']))
->from('messages')
->orderBy('created_at', 'desc')
->groupBy('conversation_id');
})
->get();
Was my first solution but that didn't work quite well. It was selecting two records as intended, but not the last ones.
I've then come up with the idea to use selectRaw instead select, which solved my issue perfectly. The final query looks like this, for any interested:
return self::whereIn('id', function($query){
$query->selectRaw('max(id)')
->from('messages')
->orderBy('created_at', 'desc')
->groupBy('conversation_id');
})
->get();

Laravel 5.3 Query - Left join some table

I'm trying to get the most recent record for each candidate_id from a ìnterviews` table.
This is what I want to achive:
I'm using Eloquent on laravel and have already tried this methods (with and without eloquent):
$candidates = DB::table('interviews')->select('interviews.*', 'i2.*')
->leftJoin('interviews as i2',
function ($join) {
$join->on('interviews.candidate_id', '=', 'i2.candidate_id');
$join->on('interviews.created_at', '<', 'i2.created_at');
}
)
->whereNull('i2.candidate_id')
->get();
and with eloquent I've tried this:
$candidates = Interview::leftJoin('interviews as i2',
function ($join) {
$join->on('interviews.candidate_id', '=', 'i2.candidate_id');
$join->on('interviews.created_at', '<', 'i2.created_at');
}
)->whereNull('i2.candidate_id')
->get();
If I change get() to toSql() I have exactly the same query that's shown on the above image, but running on laravel I'm getting always these results (this using the first method, with query builder):
Anyone know why I get this results? Is hard to understand that laravel is doing the same query that I do in HeidiSql but I get diferent results :(
Any tip?
Thanks in advance!
Because you are using ->select('interviews.*', 'i2.*') combined with ->whereNull('i2.candidate_id') I am assuming the second select parameter is overriding all fields on the interviews table with nulls, try reversing the order to ->select('i2.*','interviews.*') or not use the i2.* at all.
This is because the output ignores the alias and only uses the fieldname as element key in the returned collection.
Hope it works.
Perfect case scenario you pick the exact columns you want from each of the joined tables for e.g. it may go like this: table1.id,table1.column1,table1.column2,table2.column2 as smth_so_it_doesnt_override

How to format Laravel Eloquent query with optional sections

Im new to Laravel, but am struggling with how Eloquent queries can have optional sections.
I have the following Eloquent query at the moment:
Posts::where('approved', '=', 'Y')->orderBy('created_at', 'DESC')->take($noofposts)->skip($skipno)->get();
That works fine. However I now need to add two optional sections, which i'd like to do without having to duplicate the query each time.
I need to add AND WHERE userid=$x (looped for one or more times) if $x (which is an array) is present, if its not it should ignore then ... and finally add AND (WHERE status=$y[0] OR $status=$y[1] OR $status=$y[2]) - again if the status flags are not set, then just ignore.
Basically if no flags are set I end up with the original query, but if they are we get
Posts::where('approved', '=', 'Y')->where('userid', '=', '2')->where('userid', '=', '23')->where('status', '=', 'K')->orWhere('status', '=', 'N')->orderBy('created_at', 'DESC')->take($noofposts)->skip($skipno)->get();
I can work it out perfectly in normal PHP, but cannot understand how it would work in Laravel Eloquent.
Can anyone point me in the right direction? Neither the user guide nor any website examples seem to look at this kind of scenario!
Fist, instead of chaining orWhere I would use the whereIn function of Eloquent.
whereIn('status', $y);
The problem is, if $y is empty, the request won't work. (I think it just crashes)
So if you want to avoid controls and keep your code clean you can add a query scope in you Post model.
http://laravel.com/docs/4.2/eloquent#query-scopes
scopeOptionalWhereIn($query, $field, $array){
if(!empty($array))
return $query->whereIn($field, $array);
return $query; //return unchanged query
}
Then you can use this scope in your query:
Posts::where('approved', '=', 'Y')
->optionalWhereIn('status', $y)
->orderBy('created_at', 'DESC')
->take($noofposts)
->skip($skipno)->get();
You can probably use the same scope to deal with the userid conditions.