jeudi 29 octobre 2020

Laravel wrong limit inside function with

There are three models User Post and Image. The user has many posts, posts have many images. Also, there is a user_images function - it's hasManyThrough function. All relations work well. During the search, I wanna get users with images(max 3 for every user) and do something like that:

$users = User::where('is_active', true)
            ->with([
                'user_images' => function ($relation) {
                    $relation->limit(self::LIMIT_IMAGES);
                }
            ])->get();

Response:

[
  {
    "id": 265,
    "user_images": [
      {
        "id": 309,
        "path": "url"
      },
      {
        "id": 308,
        "path": "url"
      },
      {
        "id": 306,
        "path": "url"
      }
    ]
  },
  {
    "id": 305,
    "user_images": []
  }
]

As you can I have ONLY 3 images for all users, not for every. But if I use Lazy Eager Loading(function load) with the same limit, all works well. Can someone explain that behavior?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3owDWh3
via IFTTT

Aucun commentaire:

Enregistrer un commentaire