How to restrict data by query in magento - php

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

Related

how to get users per category and sub categories in moodle

I want to get the users per category. I'm using moodle 3.8 version. is there any method for get the users by category.
If you're looking for Moodle functions to do this, then you could probably call:
$cat = core_course_category::get($categoryid);
$courseids = $cat->get_courses(['recursive', 'idonly']);
$userids = [];
foreach ($courseids as $courseid) {
$context = context_course::instance($courseid);
$courseusers = get_enrolled_users($context, '', 0, 'u.id');
$userids = array_merge($userids, array_keys($courseusers));
}
This is, however, horribly inefficient - you'd be best off writing a custom SQL query that, given the list of course ids, will generate a list of enrolled users for all of those courses (take a look inside the code of get_enrolled_users() to see how to build such an SQL query).

Getting 2 result from one query with elequent laravel

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");

Handling complex query in laravel 5

I have simple task with complex query, 50% is done i need help for the rest of it.
Logic
I have landing pages where i choose category, then select
specifications under that category and products related to this two
filter will show in landing page. this is done
I also want have landing page when i select category without
choosing any specification and it show all products related to that
category regardless what specifications they have. need help for this
Codes
this is my controller i commented each part for better understanding
public function landings($slug){
$landing = Landing::where('slug', $slug)->Status('Active')->firstOrFail(); //find landing page
//getting landing pages category id (in case one landing page have several category involved)
$cat = DB::table('landing_categories')->where('landing_id', $landing->id)->get();
foreach ($cat as $key) {
$id[] = $key->category_id;
}
// i just add this to filter landing without specifications for if statement below **not sure about this yet**)
$spac = DB::table('landing_specifications')->where('landing_id', $landing->id)->get();
// this is where things happen (first $prod is responsible for landing with specifications and working fine, **else part** need fix to show landings without specifications.
if($spac != null){
//old
$prod = DB::table('landing_specifications')->where('landing_id', $landing->id)
->join('product_subspecification', function ($keys) {
$keys->on('product_subspecification.subspecification_id', '=', 'landing_specifications.subspecification_id');
})
->join('products', 'products.id', '=', 'product_subspecification.product_id')
->whereIn('products.category_id', $id)
->groupby('products.id')
->paginate(12);
}else{
//new
$prod = DB::table('landing_categories')->where('landing_id', $landing->id)
->join('products', 'products.category_id', '=', 'landing_categories.category_id')
->whereIn('products.category_id', $id)
->groupby('products.id')
->paginate(12);
}
return view('front.landing', compact('landing', 'prod'));
}
Hope my commenting in code above be useful to you to avoiding misunderstandings.
PS: I know I have 2 major issues here
My if statement isn't right
My else part need fix (but before fixing if() i am not able to see results of else part)
any idea?
SOLVED
I changed my if part to code below and now it is working perfectly
$spac = DB::table('landing_specifications')->where('landing_id', $landing->id)->first();
if($spac){
// rest of it...
hope it helps.

Laravel: Best way to compare two collections: whereIn?

I have a table with categories, one table with products and another table products_user which tracks the products a user owns.
When displaying products on a page it should change a button from Buy to Bought if a user owns the product.
I get the products to display through $categories->products. What is the most efficient way to find out which of these products a user already owns?
I don't want to load the entire collection of the user owned products into the memory since these could be several thousands. I also don't want to create a Mysql query for each check.
There is an option for a wherein clause. But even then I am that there is a smarter way to create this clause without looping through every product to build an array.
Can someone help me to come up with a good logic? thank you
You can make use of Constraining Eager Loads to append more information to your products. In this case, the user_id is either NULL or user_id, meaning the user is bought the product or not.
$categories = Category::with(['products' => function ($q) {
$q->select(['products.*', 'user_id'])
->leftJoin('products_user', 'user_products.product_id', '=', 'products.id')
->where(function ($q) {
$q->whereNull('user_id')->orWhere('user_id', Auth::user()->id);
});
}])->get();
foreach ($categories as $category) {
$products = $category->products;
foreach ($products as $product) {
if (empty($product->user_id)) {
// user not yet bought the product
}
else {
// user already bought the product
}
}
}

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.

Categories