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.
Related
I have a problem wanting to pass the id of Products in the subqueries.
The first code is what I have so far. The second is the way I want to do with Eloquent, but I can't.
$result = [];
Product::with(['locals.presentations'])->each(function ($product) use (&$result) {
$body['id'] = $product->id;
$body['nombre'] = $product->nombre;
$sedes = [];
$product->locals->each(function ($local) use (&$sedes, $product) {
$presentations = [];
$local->presentations->each(function ($presentation) use (&$presentations, $local, $product) {
if ($presentation->local_id == $local->id && $presentation->product_id == $product->id) {
$presentations[] = [
'local_id' => $presentation->local_id,
'product_id' => $presentation->product_id,
'presentacion' => $presentation->presentation,
'precio_default' => $presentation->price
];
}
});
...
});
return $result;
I want transform the previous code into this with Eloquent, but I can't pass the product_id into the subqueries:
$products = Product::with(['locals' => function ($locals) {
//How to get the id from Product to pass in the $presentations query ??????
$locals->select('locals.id', 'descripcion')
->with(['presentations' => function ($presentations) {
$presentations
// ->where('presentations.product_id', $product_id?????)
->select(
'presentations.local_id',
'presentations.product_id',
'presentations.id',
'presentation',
'price'
);
}]);
}])->select('products.id', 'nombre')->get();
return $products;
Product
public function locals()
{
return $this->belongsToMany(Local::class)->using(LocalProduct::class)
->withPivot(['id', 'is_active'])
->withTimestamps();
}
Local
public function presentations()
{
return $this->hasManyThrough(
Presentation::class,
LocalProduct::class,
'local_id',
'local_product_id'
);
}
You can simply use the has() method if you have set the relations correctly on the Product and Local models. This will return ONLY the products which has locals AND presentations.
If you want every product but only the locals and presentations with the product_id equals to the products.id, then you don't have to do anything. The relationship you set in your models already checks if the id matches.
$products = Product::has('locals.presentations')
->with(['locals' => function ($locals) {
$locals
->select('locals.id', 'descripcion')
->with(['presentations' => function ($presentations) {
$presentations->select(
'presentations.local_id',
'presentations.product_id',
'presentations.id',
'presentation',
'price'
);
}]);
}])->select('products.id', 'nombre')->get();
I'm in a situation where I need to display the last 5 unique commenters information at the top of the comment list as follows screenshot.
comment image
To do this. I did as follows:
Post Model
public function comments()
{
return $this->hasMany(Comment::class);
}
public function commenter_avatars(){
return $this->comments()->distinct('user_id')
->select('id','post_id','user_id','parent_id')
->whereNull('parent_id')
->with('user')->limit(5);
}
My Controller method as follows
public function index() {
$feeds = auth()->user()
->posts()
->with(['user:id,first_name,last_name,username,avatar', 'media', 'commenter_avatars'])
->orderBy('id', 'desc')
->paginate(10);
return PostResource::collection($feeds);
}
I tried to use groupBy and Distinct.. But did't work as expected.
Did I miss something? or Have there any more best way to solve this?
Thank you in advance!
Noted: I am using latest Laravel (8.48ˆ)
I don't know about your joining of post, user and comments table. But i guess, you can do something similar to following.
At first get latest 5 unique user id of one post:
$userIds = Comments::where("post_id", $post_id)->distinct("user_id")->orderBy("id")
->limit(5)->pluck('user_id');
Then, fetch those user information
$users = Users::whereIn("id", $userIds )->get();
Then, you can return those users
UPDATE
You may use map() to fetch and reorder output. Following is an idea for you:
In Controller:
public function index(Request $request) {
$skipNumber = $request->input("skip"); // this is need for offsetting purpose
$userIds = [];
$feeds = Posts::with("comments")->where("comments.user_id", Auth::id())
->skip($skipNumber)->take(10)->orderBy('comments.id', 'desc')
->map(function ($item) use($userIds){
$users = [];
$count = 0;
foreach($item["comments"] as $comment) {
if(!in_array($comment["user_id"], $userIds) && $count < 5){
$count++;
$userIds.push($comment["user_id"])
$user = User::where("id", $comment["user_id"])->first();
$users.push($user);
}
if($count == 5) break;
}
$data = [
"post" => $item,
"latest_users" => $users
];
return $data;
})->get();
return PostResource::collection($feeds);
}
My code syntax may be slightly wrong. Hopefully you will get the idea.
I have solved this issue by using eloquent-eager-limit
https://github.com/staudenmeir/eloquent-eager-limit
I'm using a method to find the records to change. Follow the code:
public function findId($id)
{
$subCategoria = $this->model::join(
'categoria', 'categoria.id', '=', 'sub_categoria.id_categoria')
->select(
'sub_categoria.id AS id_sub_categoria',
'sub_categoria.nome AS nome_sub_categoria',
'categoria.nome AS nome_categoria',
'categoria.id as id_categoria'
)
->where('sub_categoria.id', $id)
->where(
'sub_categoria.id_unidade_de_trabalho',
Auth::user()->id_unidade_de_trabalho
)
->where(
'categoria.id_unidade_de_trabalho',
Auth::user()->id_unidade_de_trabalho
)
->whereNull('sub_categoria.deleted_at')
->whereNull('categoria.deleted_at')
->first();
return $subCategoria;
}
My update method looks like this:
public function update(array $data, $id)
{
$model = $this->findId($id);
$model->nome = $data['nome'];
$model->id_categoria = $data['id_categoria'];
return $model->save();
}
Funny that when I use the find method, which is extended from Model, it works!
I have this code in Lumen 5.6 (Laravel microframework) and I want to have an orderBy method for several columns, for example, http://apisurl/books?orderBy=devices,name,restrictions,category also send asc or desc order.
Lumen's documentation says that we can use the orderBy like this
$books = PartnersBooks::all()->orderBy('device', 'asc')->orderBy('restrictions', 'asc')->get();
So, I made a function with a foreach to fill an array with different orderBy requests values and tried to put on eloquent queries without succeeding.
Can anybody help me?
use Illuminate\Http\Request;
public function index(Request $request)
{
$limit = $request->input('limit');
$books = PartnersBooks::where('is_direct', '=', 1)
->with('direct')
->whereHas('direct', function ($query) {
$query->enable()
->select(['id', 'book_id', 'name', 'devices', 'flow', 'restrictions', 'countries', 'targeting']);
})
->orderBy('id', 'asc')
->paginate($limit, ['id', 'category', 'description']);
$status = !is_null($books) ? 200 : 204;
return response()->json($books, $status);
}
You can do this:
// Get order by input
$orderByInput = $request->input('orderBy');
// If it's not empty explode by ',' to get them in an array,
// otherwise make an empty array
$orderByParams = !empty($orderByInput)
? explode(',', $orderByInput)
: [];
$query = PartnersBooks::where('is_direct', '=', 1)
->with('direct')
->whereHas('direct', function ($query) {
$query->enable()
->select(['id', 'book_id', 'name', 'devices', 'flow', 'restrictions', 'countries', 'targeting']);
});
// Foreach over the parameters and dynamically add an orderBy
// to the query for each parameter
foreach ($orderByParams as $param) {
$query = $query->orderBy($param);
}
// End the query and get the results
$result = $query->paginate($limit);
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)));