Getting 2 result from one query with elequent laravel - php

I want to get 2 result from a filter query in Laravel version 6. I want to get product table information that user can change item exist in page by a select box with name of pageitemcount and can search by a field with name of select. when user select pageitemcount and also search for an name, submit a form and below query is run . When user search anything, available filter of category must be limited to available categories. I want to show distinct product category in additional to product list.
public function productIndex(Request $request)
{
$take = 10;
$query = Product::query();
if ($request->has('pageitem')){
$take = $request->input("pageitem");
}
// Search
if ($request->has('search')){
$query = $query->where('name', $request->input("search"));
}
$availableCategoriesQuery= $query;
// Get product unique product category to show them to user
// that exist in prodcut list that show to user
$availableCategories = $availableCategoriesQuery->select("category_id")->distinct()->get();
// Get product list by pagination
$productList = $query->paginate($take);
return view('admin.manage_product', ['productList' => $productList, 'availableCategories' => $availableCategories]);
}
but when $availableCategories is executed, affected $query variable, and i cant get right result from next line, i get result of $availableCategories in $productList variable. i do'nt want to repeat my code again, how can i deal with?
the result of $availableCategories is completely true, but result of productList is $availableCategories that is paginated.

OK, I think I see the problem. You are trying to reuse the $query variable. You probably want something like this:
I assume that product_categories is the table for your product categories. You can also use the model if you want.
Also, Since the DB has no intrinsic order, you should specify an OrderBy() as well.
$take = $request->input("pageitem", 10);
$productList = Product::paginate($take)->get();
$availableCategories = DB::table('product_categories')->distinct()->get("category_id");

Related

Laravel pagination with specific foreign key

I need to make pagination in Laravel, and as I read laravel documentation here is a several way to do it. but in my cases it is a little bit complexity. So let say I've two table in my DB, table1 and table2(many to many relationship), I want to paginate table1 with specific ids. So I mean if table1 contains ids 1,2,3,4,5 ... n, I want to paginate only rows which id is 2 and 3
I have tried :
private function check_wear($type){
$products_id = array(); //here is ids which $type is set as 'ON'
$wears = DB::select("SELECT prod_id FROM wears WHERE ".$type." = 'on' "); //Select specific products ids. (in our case it is **table1**)
foreach ($wears as $wr){
array_push($products_id,$wr->prod_id);
}
return $products_id; //return array with ids which should be paginate
}
public function hat($locale){
$hat_prod_ids = $this->check_wear('coat');
$p=12;
$products = DB::table('products')->paginate($p); // 12 per page
dd($products);
my code only paginate one table with all data, is there any built-in function to somehow write a logic condition? for pagination
If you need to filter your pagination with elements which you've in $hat_prod_ids, you're able to use WhereIn() method, that one checks if your elements (in our case ids) exist in your $hat_prod_ids and returns true or false
$products = DB::table('products')
->whereIn('id',$hat_prod_ids)
->paginate($p);
add that code and now you will be able to paginate only that ids which is matched in your array

Sort elements by a value calculated on the go (not stored)

In my project I'm using Laravel 5.5 with Eloquent and Scout drivers to build a sort of search engine API endpoint.
In my scenario I have a SQL table items that has a price_factor property.
The table is also stored inside an Elasticsearch index.
With this value and with the number of the user related with that item, I can calculate the right price of the object.
An easy example is the item with id: 1 has price_factor: 2 and it is related to 5 users.
The right price of the item is 2 * 5 = 10, of course.
Now, I have to query all results and use where conditions, sorting them by that calcolated property, and return paginated results.
For example: get all items with price between 5 and 10, sort them by price and paginate by 10 elements per page.
In Eloquent I will write:
// Set filters to be applied
$filters = [
['price', '>', 5],
['price', '<', 10],
];
// Sort by "update_at", or "price"
$sort = "price";
// Order by "ASC" mode
$order = "ASC";
// Number of rows per page
$rows = 10;
// Get items
$result = Item::orderBy(
$sort,
$order
// Get related user with item record, where has...
)->with(['users'])->whereHas(
// Take users related models
'users',
// Take the model related ("user") and use filters
function($relation_model) use ($filters) {
// Apply where condition with filters
$relation_model->where($filters);
}
// Paginate for the numbers of row requested
)->paginate($rows);
How to do that if price is not a property of table items?
Should I store price inside the table and update it on every new user relation added? (or every removed relation too).
Is this the correct approach?
I was thinking about website like eBay or other real-time auction that have a similar situation of mine: how do you think they have solved?
Thanks in advance.
Assuming that you have a user_items table that keeps track of the items owned by user, I think something like this might work:
$result = Item::selectRaw('items.*, price_factor * (SELECT COUNT(id) FROM user_items WHERE user_items.item_id = items.id) AS price')
->with(['users'])
->havingRaw('price > ? AND price < ?', [5, 10])
->orderBy('price', 'asc')
->paginate($rows);
You can calculate the price on the fly and alias it. Finally you can apply a havingRaw clause to it that will check if the price is between the range it needs to be. Here's a working example of this in action.
There might be better ways to do this. I am also curious to know :)

Use two foreach loop return wrong

<?php
$id = $_GET['id'];
$getAlbumCusId = getAlbumCusId($id); //first function to get siteIds from first table from first database
foreach ($getAlbumCusId as $AlCusId) {
$proId = $AlCusId['siteid']; // got siteIds, return 2 items
$viewinv = viewinv($proId); // second function to get prices from first table from second database
foreach ($viewinv as $vinv) {
echo $vinv['price']; // but return 11 items
}
}
?>
first function return siteid from first table from first db and return two items, it's right, but now i want to get price from second function in first table in second db but it return 11 items! but i want to get price value for that two items from the first function, i know i did something wrong but i'm new in php no idea how to fix this.
GOAL: i got two items (from first function) i just want to get price for these two items.
UPDATE: problem solved;
Maybe, in second table, you have many prices of the same item (in different times), so you should order prices by date DESC and limit the result to 1 to get the last price.
make sure your query is perfect which you are using to fetch the data in second function
select price from second_table where proid = '$proid'
Make sure that you are contacting the database name to the table like (db1.tablename, db2.tablename) otherwise if the same table exists in first database ie db1 it fetch the results from db1.tablename instead of db2.tablename

Symfony2 using Query builder to load a specific ManyToMany object

My product can have many categories. In one part of the object however, I need to get a specific Category. So instead of getting all the categories and then in a for loop search for specific one, I need to get only this specific category. For that I am using query builder.
public function findProduct($id) {
$qb = $this->createQueryBuilder('p')
->addSelect(array('p', 'cat')) // many to many table
->addSelect(array('p', 'category')) // the category entity
->leftJoin('p.category', 'cat')
->leftJoin('cat.category', 'category')
->andWhere("category.id = 15") // error here
->SetParameter('id', $id);
return $qb->getQuery()->getOneOrNullResult();
}
With this query I am easily able to do $product->getCategory[0]([] since array) and get only the category that I need(in this example category with id=15)
THE PROBLEM:
However if the product doesnt have a category with a specific id.. It returns whole product null..
So If i do:
$product = $em->getRepository('MpShopBundle:Product')->findProduct($id); = null
But instead it should be like this:
$product = $em->getRepository('MpShopBundle:Product')->findProduct($id); = object
$product->getCategory() = null
How can I make this work in query builder? Is that even possible?
This should work. Instead of constraining your whole query (which is what that does) just constrain the join).
leftJoin('cat.category', 'category', 'WITH', 'category.id = 15')
This way you should get your product always & category only if id == 15.

How to restrict data by query in magento

I am new to magento and I am customizing some changes to product, catagory and home pages. I have writen the following Code to show all categories on home page
public function getRandomCategory()
{
$categoryCollection = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*');
$categoryCollection->getSelect()->order('RAND()');
return $categoryCollection;
}
How would i restrict the data by using a condition in case of * in ->addAttributeToSelect('*'); statement
A cool thing you can do to debug is to call
echo $categoryCollection->getSelect();
that will return the exact query that magento is generatingm now the addAttributeToSelect('*') what it does is to generate the 'Select * From ...' part of the query let's say that you only need to retrieve the category name
In that case you only need to do ->addAttributeToSelect('name') you_ can add multiple ->addAttributeToSelect('attribute') to retrieve multiple values.
Now if by restrict data you meant to only retrieve the categories WHERE something = tosomething else then you need to use addAttributeToFilter('atttribute', '')value
Check using_collections_in_magento for more information on the
Hope my answer helps

Categories