Reputation: 5066
I've got a Symfony entity, which has a OneToMany
mapping with an OrderBy
clause like this:
/**
* @ORM\OneToMany(targetEntity="App\Entity\News", mappedBy="category", orphanRemoval=true)
* @ORM\OrderBy({"id" = "DESC"})
*/
private $news;
Assuming I would like to only display n
entries in Twig, I would have the options to either loop over it and ignoring every thing after loop.index
n or rather use slice. However these options do have the downside, that if there are a lot of news entries, all of them will be loaded, which isn't very efficient.
Another option would be to use a Criteria in the controller or the entity to limit the amount of loaded entities. If I understood it here correctly, it should modify the doctrine query directly and thus not have any performance impact. Is this the best practice, or would it be better to have a custom query builder in the controller or a function in the repository?
Upvotes: 1
Views: 336
Reputation: 3495
Actually you can set $news
relationship as EXTRA_LAZY
and use $news->slice()
function without triggering a full load as stated in official documentation:
If you mark an association as extra lazy the following methods on collections can be called without triggering a full load of the collection:
Collection#contains($entity) Collection#containsKey($key) (available with Doctrine 2.5) Collection#count() Collection#get($key) (available with Doctrine 2.4) Collection#slice($offset, $length = null)
Therefore your declaration should look like the following:
/**
* @ORM\OneToMany(targetEntity="App\Entity\News", mappedBy="category", orphanRemoval=true, fetch="EXTRA_LAZY")
* @ORM\OrderBy({"id" = "DESC"})
*/
private $news;
Upvotes: 1