Doctrine 2: Pagination with Association Mapping
I'm wondering how you can paginate the results from mapping entity associations in Doctrine 2? for example
class Customer {
/**
* @OneToMany(targetEntity="Order")
*/
private $orders;
}
can be used as such:
$customer->getOrders();
which will return a collection of objects Order
.
The problem is that there are a lot of order objects.
We can use Doctrine\ORM\Tools\Pagination\Paginator
when creating custom queries, however I see no way to connect to generate queries when using association mapping.
class Paginator {
/**
* @param Query|QueryBuilder $query A Doctrine ORM query or query builder.
*/
function __construct(
//....
source to share
If you use EXTRA_LAZY fetch mode, Doctrine will not fetch all objects when wetting a collection. It will only fetch the subset it needs when you use the slice () method on the collection.
class Customer {
/**
* @OneToMany(targetEntity="Order", fetch="EXTRA_LAZY")
*/
private $orders;
}
$cust = new Customer;
$orders = $cust->getOrders()->slice(100, 50);
You will need to check how this interacts with pagination.
source to share
Collections have a filtering API that lets you trim pieces of data from a collection. If the collection has not yet been loaded from the database, the filter API can run at the SQL level to provide optimized access to large collections. Doctrine Filter Collections
class Customer {
/**
* @OneToMany(targetEntity="Order")
*/
private $orders;
public function getOrders($offset = 0, $limit = 30){
$criteria = Criteria::create()
->setFirstResult($offset)
->setMaxResults($limit);
return $this->orders->matching($criteria);
}
}
$cust = new Customer;
$orders = $cust->getOrders(50, 100);
source to share