Pagination using Doctrine and ZF2 - php

i am trying to implement Pagination Using ZF2 and Doctrine.
What i am trying to do here is to fetch data from An associated table lets say 'xyz'.
Where as my categories table is doing one to many self referencing on its own PK.
MY catgories tables has following feilds
ID (PK)
Created_at
Category_id (self referencing PK)
My XYZ table lets say it is called Name table has
ID (PK)
Category_id(FK)
name
Detail
This is what i am trying to do to fetch data
public function allSubcategories($id, $column, $order) {
$repository = $this->entityManager->getRepository('Category\Entity\Category');
$queryBuilder = $repository->createQueryBuilder('category');
$queryBuilder->distinct();
$queryBuilder->select('category');
$queryBuilder->join('Category\Entity\CategoryName', 'category_name', 'WITH', 'category.id = category_name.category');
$queryBuilder->orderBy("category.status");
$q = $queryBuilder->getDql();
return $query = $this->entityManager->createQuery($q);
}
And in my controller this is what i am doing
public function subcategoryAction() {
///////////////////////////InPut Params Given for the pagination
$category_id = (int) $this->params()->fromRoute('id', 0);
$page = (int) $this->params()->fromRoute('page', 0);
$column = $this->params()->fromQuery('column');
$order = $this->params()->fromQuery('order');
$categoryModel = $this->getServiceLocator()->get('Category');
$categoryModel->category = $category_id;
$perPage = 10;
$request = $this->getRequest();
if ($request->isGet()) {
$view = new ViewModel();
$query = $categoryModel->allSubcategories($category_id, $column, $order);
$paginator = new ORMPaginator($query);
$paginator = new \Zend\Paginator\Paginator(new
\Zend\Paginator\Adapter\ArrayAdapter(array($paginator)));
$paginator->setCurrentPageNumber($page);
$paginator->setItemCountPerPage(2);
}
return array('id' => $category_id, 'view' => $paginator);
}
Now i am not getting results with pagination implemented can some 1 guide me about what i am missing?

You are using the wrong paginator there. Instead, you can use the one by DoctrineORMModule ( see DoctrineORMModule\Paginator\Adapter\DoctrinePaginator).
It may not be very obvious, but the logic is similar to what you already wrote:
use DoctrineORMModule\Paginator\Adapter\DoctrinePaginator as PaginatorAdapter;
use Doctrine\ORM\Tools\Pagination\Paginator as ORMPaginator;
use Zend\Paginator\Paginator as ZendPaginator;
$query = $categoryModel->allSubcategories($category_id, $column, $order);
$paginator = new ZendPaginator(new PaginatorAdapter(new ORMPaginator($query)));

Related

Symfony 4 - populate array with the users of type ROLE_FITTER

Symfony 4 app using FOSUserBundle.
Trying to list users with a particular role (ROLE_FITTER) in a dropdown menu using jquery/ajax.
I'm trying to add an Action in my APIController that will get the list of users with role ROLE_FITTER and return a JSON array with them in it - so can then populate the dropdown with list of these users.
I have tried to pull together some different examples, but not sure how to correctly build the query:
namespace App\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class APIController extends AbstractController
{
/**
* Returns a JSON string of the Fitters with their id.
*
* #Route(/profile/booking/new/fitters)
* #param Request $request
* #return JsonResponse
*/
public function listFitters(Request $request)
{
// Get Entity manager and repository
$em= $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$qb->select('u')
->from('userBundle:User', 'u')
->where('u.id = :user')
->andWhere('u.roles LIKE :roles')
->setParameter('user', $id)
->setParameter('roles', '%"' . $role . '"%');
$user = $qb->getQuery()->getResult();
// Serialize into an array the data that we need, in this case only name and id
$responseArray = array();
foreach ($users as $user) {
$responseArray[] = array(
"id" => $user->getId(),
"name" => $user->getName()
);
}
// Return array for dropdown
return new JsonResponse($responseArray);
}
}
How do I populate this array with the users of type ROLE_FITTER?
Well using serialized strings in sql is never a good idea, no idea why such a popular bundle would do that, but it is what it is.
Your query as written checks for a user with specific id, and role. but you never provide the id or role!.
I dont think you want to query by id, so the correct query should be something like this:
public function listFitters(Request $request)
{
// Get Entity manager and repository
$em= $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
//set required role
$role = 'ROLE_FITTER';
$qb->select('u')
->from('userBundle:User', 'u')
->where('u.roles LIKE :roles')
->setParameter('roles', '%"' . $role . '"%');
$user = $qb->getQuery()->getResult();
// Serialize into an array the data that we need, in this case only name and id
$responseArray = array();
foreach ($users as $user) {
$responseArray[] = array(
"id" => $user->getId(),
"name" => $user->getName()
);
}
// Return array for dropdown
return new JsonResponse($responseArray);
}
Probably you should only select the fields you want (id, name) and avoid the array building loop, but i am not particularly familiar with symfony / doctrine so not sure of the correct syntax

Paginate Results of Model Laravel

I have a problem with pagination in laravel 5.3
The code:
public function deals()
{
return $this->belongsToMany('App\Models\ListsDeals', 'list_has_deals' , 'list_id', 'deal_id')->withPivot('list_id');
}
public function form_edit_list( $id ){
$list = Lists::find( $id );
PAGINATE THIS -----> $deals = $list->deals;
$user = User::find( $list->id_user );
$categoriesArray = ListsCategories::all();
$featuresArray = ListsFeatures::all();
$images = ListsGalleries::all();
return view( "admin.forms.form_edit_list" )
->with( "list", $list )
->withCategoriesArray( $categoriesArray )
->withFeaturesArray( $featuresArray )
->withImages( $images )
->with( "user", $user );
}
I have tried this,
$deals = $list->deals->paginate(5);
How can I paginate the results of deals ?
Because paginate is not a method of that.
I believe you can add the paginate() call to the deals() relationship definition (which will paginate all uses of it).
That may not be ideal, so you can also do $deals = $list->deals()->paginate();
$list->deals is a collection of items, while $list->deals() is an Eloquent query builder instance you can make further adjustments to before fetching the reuslts.

Laravel:: reuse article id into new table

I need to be able to make a "like" system. I have three tables. Users, Articles, Likes.
In the Articles table I have the id, title, body. In Likes I have id, user_id, and article_id.
So when a person presses like on the article I fill the table with their user id and the article_id.
However I'm running into the problem of adding the id. This is basic to most I know, I have seen the laravel videos but its still new to me.
Here is what I have in the article controller.
$article = new Article();
$article->body = 'new article body';
$article->title = 'new article Title';
$article->type = 'fashion';
$article->save();
$articles = Article::where('type', 'fashion')->get();
//$articles = Article::all();
return view('articles.index', compact('articles'));
public function store()
{
$request = Request::all();
$likes = new like();
$likes ->article_id = Article::find($id);
$likes->user_id = Auth::user()->id;
$name = Auth::user()->name;
$likes->save();
$followers = new Follower();
$followers->follower_id = Auth::user()->id;
$followers->user_id = $request['user_id'];
$name = Auth::user()->name;
$followers->save();
return redirect('article');
}
You are trying to use a variable which doesn't exist. Variable $id being used on this line
$likes ->article_id = Article::find($id);
is not initialized anywhere. Maybe you are expecting it to be on the Request? So in that case, $request->id in that case.
Also if your model is called Like than you should fix the case on this line $likes = new like(); to $likes = new Like();.

Yii - findAll with order by

How to findAll with specific column with order by desc ?
Code bellow worked and find all from the developer id
$id = Yii::app()->user->getState('id');
$models = Games::model()->findAll('developer_id='.$id);
Code bellow worked and ordered
$models = Games::model()->findAll(array('order'=>'status'));
When I mixed together then only worked for findAll developer_id='.$id doesn't order by
$id = Yii::app()->user->getState('id');
$models = Games::model()->findAll('developer_id='.$id,array('order'=>'status'));
Any suggestion to do that ? Thanks
In your model, add this function:
public function scopes() {
return array(
'bystatus' => array('order' => 'status DESC'),
);
}
Now you can do the query like this:
$models = Games::model()->bystatus()->findAll('developer_id='.$id);
=====
Bonus: You can also add this function in your model:
public function bydeveloper($devId) {
$this->getDbCriteria()->mergeWith(array(
'condition' => 'developer_id = '.$devId,
));
return $this;
}
Now you can do the query like this:
$models = Games::model()->bystatus()->bydeveloper($id)->findAll();
you can try this -
$id = Yii::app()->user->getState('id');
$model = Games::model()->findAll(array("condition" => "developer_id = '".$id."'","order" => "status"));
its should be work
You can try use criteria:
$id = Yii::app()->user->getState('id');
$criteria=new CDbCriteria;
$criteria->compare('developer_id',$id);
$criteria->order='status DESC';
$models = Games::model()->findAll($criteria);
It's not the best way but you can do:
$models = Games::model()->findAll('developer_id='.$id.' order by status DESC');
Model::find()->where([['attribute'=>'value']])->orderBy(['attribute'=>SORT_DESC])->all();

Where condition in Doctrine and Zend Framework 2 Pagination

I'm unable to make a where condition to work with Doctrine and Zend framework 2 pagination.
My code is given below.
public function indexAction(){
$em = $this->getEntityManager();
$repository = $em->getRepository('Catalog\Entity\Category');
$queryBuilder = $repository->createQueryBuilder('Category');
$adapter = new DoctrinePaginator(new ORMPaginator($queryBuilder));
$paginator = new Paginator($adapter);
$paginator->setDefaultItemCountPerPage(9);
$page = (int)$this->params()->fromQuery('page');
if($page) $paginator->setCurrentPageNumber($page);
$view = new ViewModel(
array('paginator' => $paginator)
);
return $view;
}
I want to get Categories for which 'enabled' column value is 1.
The alternate way I got is create DQL query but I don't get the benifit of zend framework 2 pagination.
$repository->createQueryBuilder('Category')->where(array('enabled' => 1));
I want to use my top code way because it helps me to take full benefit of zend framework 2 pagination but how can I specify a where condition in it?
I solved it by using QueryBuilder of Doctrine. Find the code below to add condition along with Zend Framework 2 pagination.
public function indexAction(){
$em = $this->getEntityManager();
$repository = $em->getRepository('Catalog\Entity\Category');
$queryBuilder = $repository->createQueryBuilder('category')
->where('category.enabled = 1')
->orderBy('category.sortOrder', 'ASC');
$adapter = new DoctrinePaginator(new ORMPaginator($queryBuilder));
$paginator = new Paginator($adapter);
$paginator->setDefaultItemCountPerPage(9);
$page = (int)$this->params()->fromQuery('page');
if($page) $paginator->setCurrentPageNumber($page);
$view = new ViewModel(
array('paginator' => $paginator)
);
return $view;
}

Categories