Laravel eager loading with limit
My solution linked by @berbayk is cool if you want to easily get latest hasMany
related model.
However, it couldn't solve the other part of what you're asking for, since querying this relation with where
clause would result in pretty much the same what you already experienced - all rows would be returned, only latest
wouldn't be latest in fact (but latest matching the where constraint).
So here you go:
the easy way - get all and filter collection:
User::has('actions')->with('latestAction')->get()->filter(function ($user) {
return $user->latestAction->id_action == 1;
});
or the hard way - do it in sql (assuming MySQL):
User::whereHas('actions', function ($q) {
// where id = (..subquery..)
$q->where('id', function ($q) {
$q->from('actions as sub')
->selectRaw('max(id)')
->whereRaw('actions.user_id = sub.user_id');
})->where('id_action', 1);
})->with('latestAction')->get();
Choose one of these solutions by comparing performance - the first will return all rows and filter possibly big collection.
The latter will run subquery (whereHas
) with nested subquery (where('id', function () {..}
), so both ways might be potentially slow on big table.
Laravel limit eager loading for each model
There is no native support for this in Laravel.
I created a package for it: https://github.com/staudenmeir/eloquent-eager-limit
Use the HasEagerLimit
trait in both the parent and the related model.
class Conversation extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
class Message extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
Then simply chain ->take(25)
call to your eager-load query (which seems you already do).
You could even use ->offset(...)
and ->skip(...)
(see repository readme for details).
How to eager load only 1 result from many to many relationship Laravel
I realized its too complex to achieve it myself and ended up using the eloquent-eager-limit package from staudenmeir (big thanks to him, save me hours of work :) )
here's my model
class Application extends BaseModel {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
public function applicants() {
return $this->belongsToMany(Applicant::class);
}
public function oneApplicant() {
return $this->applicants()->limit(1);
}
}
Then I was able to use it on my controller
return Application::stage( $stages )
->stagenot($stageNot)
->refered( $refered, $term )
->with([
'oneApplicant',
'oneApplicant.onePhone:model_id,number',
'oneApplicant.oneAddress:model_id,state'
])->orderBy('created_at','desc')->paginate( $count );
Laravel eloquent eager loading limit error
You have made a mistake at this line:
$q->where("professions.name", "like", "%".$query."%");
You need to concatenate the variable.
You're getting this error because with()
takes an associative array in order to constrain eager loads. Try:
$professions = Profession::whereHas("users", function($q) use($query) {
$q->where("professions.name", "like", "%".$query."%");
})->withCount('users')->with(['users' => function($q) {
$q->take(5);
}])->paginate(10);
Related Topics
How to Install/Enable the PHP Phar Extension
Call a C Program from PHP and Read Program Output
Composer Installing: the JSON Extension Is Missing
Executing a Shell Script in Background with PHP
PHP Session Side-Effect Warning with Global Variables as a Source of Data
How to Get the Character from Unicode Code Point in PHP
Simple HTML Dom: How to Remove Elements
PHP Commands Out of Sync Error
How to Check If There Is a There Is a Wget Instance Running
PHP Failed to Open Stream: Is a Directory
Centos 7/Apache/PHP - Mkdir(): Permission Denied
Execute Commands on Remote MAChine via PHP
How to Chain Method on a Newly Created Object
Header in PDF Page Using Dompdf in PHP
How to Solve Incompatible with SQL_Mode=Only_Full_Group_By in Laravel Eloquent