简体   繁体   中英

Laravel Eloquent query scope with join that uses DB::raw

I have a query scope from a L5.1 app that is not working on L5.7. The scope adds a simple join with a DB::raw statement like so:

    public function scopeLatest($query)
    {
        return $query->join(DB::raw('(SELECT patient_id, MAX(created_at) created_at FROM referral_reports GROUP BY patient_id) r2'), function ($join) {
                            $join->on('referral_reports.patient_id', '=', 'r2.patient_id');
                            $join->on('referral_reports.created_at', '=', 'r2.created_at');
                            });
    }

Using this scope on L5.1 worked great, but in 5.7, the entire join is omitted from the query and no error is thrown. I had to use DB::enableQueryLog() on both apps to see that the resulting queries were different.

Any idea why this isn't working in 5.7?

Here is an example of using this scope via a static method on the model:

        $entries = self::inStudies($studies)
                       ->calltime($startDate, $endDate)
                       ->latest()
                       ->omitdeleted()
                       ->get();

inStudies, calltime, latest, omitdeleted are all query scopes.

Your scope doesn't work because it conflicts with latest method. Just rename this scope and it will work.

latest / oldest methods have been added in Laravel 5.3

Did you add use DB; on top?

Try these

public function scopeLatest($query){

return $query->join('referral_reports.patient_id', '=', 'r2.patient_id')

    ->join('referral_reports.created_at', '=', 'r2.created_at')

    ->select(DB::raw('SELECT patient_id, created_at) r2'));
}

Normally i would run the group by from controller

Model::latest()->max('created_at')->groupBy('patient_id')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM