How can I eager load only one from many to many relationship?
I have two models Application & Applicant
Models\Application.php
public function applicants() {
return $this->belongsToMany(Applicant::class);
}
public function oneApplicant() {
return $this->applicants()->first();
}
I'm wanted to paginate on the applications and want to load only one applicant (if they have.)
return Application::stage( $stages )
->stagenot($stageNot)
->refered( $refered, $term )
->with(['oneApplicant'])
->orderBy('created_at','desc')->paginate( $count );
But it isn't working.
Getting the first result like this return $this->applicants()->first()
will produce an error Call to undefined method Illuminate\Database\Query\Builder::with()
If I also put a limit instead of first return $this->applicants()->limit(1) it will only show one applicant to the last collection.
I also tried to modify the query directly on eager loading call to get the first row
return Application::with(['applicants', => function( $query ) {
$q->first();
}])->orderBy('created_at','desc')->paginate( $count );
But the result is the same as adding a limit(1) on directly on the relation, it will only add one applicant to the last item from collection and the other item have empty array value
Can anybody help :)
Thanks