Load particular category by using collection - magento-1.9

I am new to magento , now I am trying to load particular category instead of using load-> , I need to used getCollection().How I retrieve particular category collection.

Without knowing why you are trying to avoid the category model's load method or what you want to use to filter your collection it's hard to give a better answer, but here are some methods for loading a category collection which filters on an array of category ID's or a category name.
$collection = Mage::getModel('catalog/category')->getCollection();
// From here it really depends on how you want to set up your SELECT statement
$collection->addIdFilter($ids_array);
// OR
$collection->addFieldToFilter('name', ['eq' => $category_name]);

Related

Rails, MySql, JSON column which stores array of UUIDs - Need to do exact match

I have a model called lists, which has a column called item_ids. item_ids is a JSON column (MySQL) and the column contains array of UUIDs, each referring to one item.
Now when someone creates a new list, I need to search whether there is an existing list with same set of UUIDs, and I want to do this search using query itself for faster response. Also use ActiveRecord querying as much as possible.
How do i achieve this?
item_ids = ["11E85378-CFE8-39F8-89DC-7086913CFD4B", "11E85354-304C-0664-9E81-0A281BE2CA42"]
v = List.new(item_ids: item_ids)
v.save!
Now, how do I check whether a list exists which has item ids exactly matches with that mentioned in query ? Following wont work.
list_count = List.where(item_ids: item_ids).count
Edit 1
List.where("JSON_CONTAINS(item_ids, ?) ", item_ids.to_json).count
This statement works, but it counts even if only one of the item matches. Looking for exact number of items.
Edit 2
List.where("JSON_CONTAINS( item_ids, ?) and JSON_LENGTH(item_ids) = ?", item_ids.to_json, item_ids.size).count
Looks like this is working
You can implement a has many relation between lists and items and then access like this.
List.includes(:item).where('items.id in (?)',item_ids)
To implement has_many relation:
http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

how to track changes of relation between two models in yii2

I have two models with a simple 1-n relation (category and item with category_id). I would like to show how much items there is in the category. I would like to have the number cached rather then always doing the count, so I have an extra field in category table called "total_items_count".
How to best do this total count triggering, when to call the "countUpdate" function since the relation could change from several places (backend, api, frontend...).
My initial plan was to use AFTER_UPDATE event, but "link()" must be called after the item is stored in database (on adding new item at least) so then I do not know which category is the item related to. I also need to know the old category, in case item goes from one category to another. In the backend controller I am using $item->link('category', $categoryObj); as I might change this relation to n-n someday.
Any advice on how to have complete control if the link between item and category changes and then update the count for the old and new linked category?
Thanks
The first and most important thing you need to now, is that you need to update the category count field via the ActiveRecord::updateCounters() method, in order to prevent incorrect update from multiple places. So you can do one of those things:
In the category item model you can do the following:
public function save($runValidation = true, $attributeNames = null)
{
if (parent::save(runValidation, attributeNames)) {
$this->category->updateCounters(['total_items_count' => 1]);
return true;
}
return false;
}
Or you can write a centralized component (let's say app\components\Category) which you will call from the whole application. This component will have a method that saves an item. For example:
public function saveItem($category, $item)
{
if ($item->save()) {
$item->link('category', $category);
$category->updateCounters(['total_items_count' => 1]);
return true;
}
return false;
}
Of course, when you delete an item, you will call:
$category->updateCounters(['total_items_count' => -1]);
See the ActiveRecord::updateCounters() API
From the Yii2 documentation:
Note: If you use yii\db\ActiveRecord::save() to update a counter column, you may end up with inaccurate result, because it is likely the same counter is being saved by multiple requests which read and write the same counter value.
If you need to keep track of which is the old category, just create another column let's say "old_category" to the category item table and when you change the category of the item put the old category id there, and the new category id to the category_id column.
Does that helps? If you have any questions, please ask!

iterate over instance field containing multiple instances?

This is my fist time using django and I'm having some problems to understand how data is stored, so I can not really use it as I want to. I made many researches but I don't find any related question probably because I don't have the right keywords.
In my app model I created a WebPage and Count class:
class Count(models.Model):
date = models.DateField(default=date.today)
count = models.IntegerField(default=0)
class WebPage(models.Model):
link = models.CharField(max_length=60)
id = models.AutoField(primary_key=True)
clicks = models.IntegerField(default=0)
stats = models.ForeignKey(Count)
Then I created a WebPage object with multiple Count objects and I'd like to create a method to retrieve the sum of the count instances.
def get_clicks(self):
self.clicks=0
for object in self.stats:
self.clicks+=object.count
return str(self.clicks)
but I get the error 'Count' object is not iterable which is logic because I defined self.stats as an single Count object. I told my self that if the Count instances are not stored in self.stats they could be stored as "global" Count instances so I iterated over the object instances for object in self._meta.fields but the multiple Count instances are missing:
statistics.WebPage.link
statistics.WebPage.id
statistics.WebPage.clicks
statistics.WebPage.stats
And I think that iterate over the "global" Count objects it is not an option because I could not know which Count instance belong to which WebPage.
Where the self.stats Count instances hidden? Thanks for the help!
(I'm using django 1.7)
The problem is that your ForeignKey is the wrong way round. The model that the FK is defined in is the "many" side of the one-to-many relationship. That is, the way you have it, each Count has many WebPages, whereas I think you want the other way round.
Then you can sum the counts attached to your web page in one go via aggregation:
from django.db.models import Sum
total_clicks=my_web_page.count_set.aggregate(Sum('count'))
or, to get clicks for a whole queryset of webpages:
my_web_page_queryset.annotate(clicks=Sum('count__count'))
web_page = Webpage.objects.get(pk=1)
def get_clicks(web_page):
return web_page.contact_set.count()
This will work if you get a single Webpage. If you get a group of webpages, you can loop through them and call get_clicks for each.

cakephp retrive data from one table excluding the associated tables

I am struggling with a basic problem. i am using cake php 2.5. i try to apply the find query in the company model and receiving all the data from companies and with its associations, but i only want to receive the data from company table and want to exclude the data from rest of relationships, can anyone help me with this. below are my queries.
$this->loadModel('Company');
$fields=array('id','name','logo','status');
$conditions=array('status'=>1);
$search_companies = $this->Company->find('first',
compact(array('conditions'=>$conditions,'fields'=>$fields)));
print_r($search_companies);die();
echo json_encode($search_companies);die();
With out seeing your data output, I am just going to take a stab at the problem.
Inside your $search_companies variable you are getting a multidimensional array probably with the other values of the other tables.
Why not just select the one array:
$wantedData = $search_companies['Company'];
// The key Company (which is the model) should be the data you are wanting.
Try setting model's recursive value to -1
$this->Company->recursive = -1;
$search_companies = $this->Company->find('first',
compact(array('conditions'=>$conditions,'fields'=>$fields)));
With this you will not fire the joins queries and therefore you only retrieve model's information.
Cakephp provide this functionality that we can unblind few/all associations on a any model. the keyword unbindModel is used for this purpose. inside the unblindModel you can define the association type and model(s) name that you want to unblind for that specific association.
$this->CurrentModelName->unbindModel(array('AssociationName' => array('ModelName_Youwwant_unblind')));

Build and Array of Arrays from query result with <cfloop>

I've got records in my MySQL projects database that have several boolean flags to help me sort the data. I have 3 categories planning, landscape, and environmental and 4 classes (or subcategories) for each category; industrial, government, education, residential.
My goal is to use ColdFusion to create and store the project_id numbers in an array of some kind that will basically have the projects sorted by category and class. That way I can grab just the industrial projects in the planning category and construct a link to that project.
So, the first position in the array would be planning and inside that first position would be the 4 classes, then, within that would be all of the project_id numbers that returned true for those particular criteria.
The logic I'm looking to create goes like this...
Loop over the query result, if planning = true and industrial = true, place the project id # into the planning array inside the industrial array.
How can I use <cfloop> to loop over the list of project records, recognize the category and class flags and construct a clean and usable dataset? Can this be handles in the query in some way?
Figure out the desired data structure
look at your existing data structure
figure out the algorithm to translate from one to the other
You may cfloop the query, and use a large cfswitch (or large set of if-then-else) to figure out how you want to store the id in your desired data structure. Or if you can map the class/category name as a struct key, then it might be easier.
Or you may use cfoutput group="" if it helps (cfloop group="" is available on in CF10+)
Finally, maybe you don't even need the data structure, just use Query of Queries wherever you need.
You may be able to utilize the Underscore.cfc library for this. For example, you could use the filter function to extract an array of structs representing the query rows you want:
planningArray = _.filter(queryResult, function(row){
return (row.planning == true && row.industrial == true);
});