The limit of Laravel's eloquence in relation that relates

I have a relationship from category to content, and I want a limit of 4 content for each category.

I would like to limit the result of a content relationship that is related to languages

My code

Category::with(['contents.languages' => function($query){
        $query->limit(4);
    }])
        ->get();

But I see that the limit works on languages , not the content that I need - this is a restriction on the content

+4
source share
6 answers
Functions

take () and limit () will not work with heavy loading if you get the parent model more than one using the get () method.

So you need to do a different path,

$categories = Category::with('contents')->get();

$categories foreach, ,

$contents = [];
foreach($categories as $category){
   $category->limitedContents = $category->contents()->with('languages')->limit(4);
}

4 limitedContents.

. limitedContents, .

+2

n

, , N + 1 . , :

  $categories = Category::get(); 
  $categories->each(function ($category) {
     $category->load([ 'contents' => function ($q) {
             return $q->limit(4);
     }, 'contents.languages']);
  });

? , , . , , N + 1 .

+1

It also works

foreach(Category::with('contents')->get() as $category)
   {
        foreach($category->contents->take(4) as $content)
        {
            $languages = $content->with('languages')->get();
            foreach($languages as $language)
             {
                //your code
             }
        }
   }
+1
source

try it

Category::with([
   'contents' => function($q) { $q->limit(4); },
   'contents.languages'
])->get();
0
source

You should try the following:

Category::with(['contents.languages'])->limit(4)->get();
0
source

You can set an additional method in the model Categoryand make a call with this:

public function contentsTake4()  
{
    return $this->hasMany('App\Content')->limit(4);
}

Then you should call it in the controller as follows:

Category::with('contentsTake4.products')->get();
0
source

Source: https://habr.com/ru/post/1695974/


All Articles