How to limit records with with() method User::with(['posts' => function($query) {
$query->where('created_at', '>', $someDate);
}])->get();
It works fine.
Now I want to limit the no. of posts and i used
User::with(['posts' => function($query) {
$query->where('created_at', '>', $someDate)->take(5);
}])->get();
but didn't return any value.
I would try:
User::with(['posts' => function($query) {
$query->where('created_at', '>', $someDate);
}])->take(5)->get();
User::with(['posts' => function($query) {
$query->where('created_at', '>', $someDate);
}])->take(5);
You can either update the relation to the example below or use take on the query, so not in the callback but after the callback
// App\User.php
class User extends Model {
public function posts()
{
return $this->hasMany('App\Post');
}
public function limitPosts()
{
return $this->hasMany('App\Post')->limit(5);
}
}
Now you can do this
User::with(['limitPosts' => function($query) {
$query->where('created_at', '>', $someDate);
}])->get();
@bobbybouwmann I tried your method but didn't get desired result.. Instead it doesn't return any value or only some.
When I remove ->limt(10) then it return all records...
Once again, show your code, we can't predict your code!
This is in Menu.php model
public function limitNewsTen(){
return $this->hasMany('App\News','category_id');
}
This is in my HomeController.php
$categories = Menu::whereStatus(0)->orderBy('page_category_order','asc')
->with(['limitNewsTen'=>function($query){
$query->orderBy('id','desc');
}])->get();
@bobbybouwmann Once again the question: I want all menu with 10 news on each.
Mmh looks fine to me.. You are sure you get the correct data if you leave of limit()?
Yaa.. but If I do this:
public function limitNewsTen(){
public function limitNewsTen(){
return $this->hasMany('ProNews\News','category_id')->limit(10)->whereStatus_id(1)->whereStatus(0)->orderBy('id','desc');
}
In Home controller :
$categories = Menu::whereStatus(0)->orderBy('page_category_order')->get();
And View:
@foreach ($categories as $category)
@foreach ($category->limitNewsTen as $news)
{!! $news->title !!}
@endforeach
@endforeach
@bobbybouwmann Now it works fine but isn't there any way we can do where,orderBy stuffs on controller instead in model?
->get()
->map(function ($category) {
$category->post = $category->post->take(3);
return $category;
});
Please sign in or create an account to participate in this conversation.