So I want to get requests which have last status equal to given status I've tried with first() but it gives me an error and limit is not working
$requests = Request::whereHas('requestStatus', function ($query) use ($status) {
return $query->where('status',$status)->orderBy('updated_at', 'desc')->limit(1);
})->get();
Controller
public function listByStatus($status)
{
$requests = Request::whereHas('requestStatus', function ($query) use ($status) {
return $query->where('status',$status)->orderBy('updated_at', 'desc')->limit(1);
})->get();
return view('admin.request.list',compact('requests','status'));
}
Model Request
public function requestStatus()
{
return $this->hasMany('App\RequestStatus');
}
Migration RequestStatus
Schema::create('request_status', function (Blueprint $table) {
$table->increments('id');
$table->integer('request_id')->unsigned();;
$table->foreign('request_id')->references('id')->on('requests');
$table->string('status');
$table->string('image')->nullable();
$table->timestamps();
});
Try this:
$requests = Request::select('requests.*')
->join('request_status', 'requests.id', 'request_status.request_id')
->where('request_status.status', $status)
->where('request_status.id', function($query) {
$query->select('id')
->from('request_status')
->whereColumn('request_id', 'requests.id')
->orderByDesc('updated_at')
->limit(1);
})
->get();
To avoid N+1 problem you can use the power of the collections :
$requests = Request::whereHas('requestStatus', function ($query) use ($status) {
return $query->where('status',$status)->orderBy('updated_at', 'desc');
})->get()
->map(function($request) {
$request->setRelation('requestStatus', $request->requestStatus->take(1));
return $request;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With