CodeIgniter ActiveRecord Multiply - codeigniter

I'm trying to work out the total value of all the products in my inventory. Each product in the table has a price and quantity. So I need to multiply each product's price by the quantity and then add all of these together to get a total for all products. From a previous question, I now have the MySQL query to do this:
select sum(product_price*product_quantity) as stockvalue from products
But now I'm trying to work out the correct way to do this with CodeIgniter's ActiveRecord.
Grateful for any advice on this. I've looked in the docs but can only find select_sum() for one field, rather than the sum of multiplying two together.
I have tried using the following:
public function getStockValue() {
$this->db->select('sum('product_price'*'product_quantity') as stockvalue', FALSE);
$this->db->from('products');
$query = $this->db->get();
return $query->row()->stockvalue;
}

Try this:
$this->db->select('sum(`product_price`*`product_quantity`) as stockvalue', FAlSE);
I'm not sure if you need the second argument. I haven't worked with CI for quite awhile.

$this->db->select('sum(product_price) * sum(product_quantity) as stockvalue', FALSE);

Related

Laravel Eloquent duplicate distinct row

Let's consider the image above. I would like to show duplicated entries as one entry and also I want to show the sum of the "stock" column. In this case it should be 5722.
Is it possible to do it using Eloquent? Or what are the best ways to do it?
Not sure how your database / query is built but you could maybe use something like that:
Item::groupBy('item_name')
->selectRaw('*, sum(stock) as sum')
->get();
It will return a collection of Item with an additional “sum” field
This will group the result with same medicine and supplier name and sum up the stock.
$result = Model_Name::groupBy('medicine_name','supplier_name')
->selectRaw('*, sum(stock) as sum')
->get();
Try this. Hope it might help you.

How do I display all products by descending SKU #'s in Magento?

I am trying to display all products on my website in every category by descending SKU #'s. Can't seem to figure out how to do this, any ideas?
The following snippet will give you the collection you want, you may need to add pagination yourself if necessary.
$collection = Mage::getModel("catalog/product")->getCollection();
$collection->setOrder('sku', 'DESC');
You'll also need to join on any extra attributes with joinAttribute(), since the catalog_product database storage follows the EAV pattern.
I think this should help. Go to Admin->Catalog->Attributes->Manage Attributes find SKU and enable SKU first. Then you have to go app/code/core/Mage/Catalog/Block/Product/List/Toolbar.php. Find at line 119 and change
protected $_direction = 'asc';
Change to
protected $_direction = 'desc';

How To Efficiently Loop Through Product Collection and Set Attribute Data

I am trying to bulk update some of my product attributes. Effectively I am using this code:
foreach ($outOfStock as $product) {
$product->setData('attribute',20);
$product->save();
}
However I am getting a php 60 second timeout, when I check, it only got as far as about 15 products. It seems to me that this is not the most efficient way to achieve this.
What is the correct way to update products in bulk?
If your attribute is mass-updatable, you may refer to the corresponding core code from Mage_Adminhtml_Catalog_Product_Action_AttributeController::saveAction(), especially this method :
Mage::getSingleton('catalog/product_action')
->updateAttributes($productsIds, $attributesData, $storeId);

Magento : get related products from both product ID and current category ID

I totally begin with Magento during my training period. I've been working on a project for two weeks now and sometimes I can't figure out how to proceed.
I'm gonna try to represent my categories tree :
- accessories
* visors
* communication systems
* other
- helmets
* a lot of subcategories and subcategories...
My actual problem is : I'm in one of the accessories subcategory (for example visors). I added a form with a select allowing to choose a helmet model. When the select is submitted, I'd like to display the list of visors related to the chosen helmet model (that is actually a virtual product).
I can get the current category ID (in this case, visors) and the virtual product ID (so the helmet model). But I can't figure out how to display related products by both product ID and category ID.
I tried stuff like this :
$relatedProducts = Mage::getModel('catalog/product_link')
->getCollection()
->addCategoryFilter($myCurrentCat)
->addFieldToFilter('product_id',$myVirtualProductId)
->addFieldToFilter('link_type_id','1');
But it seems not to work.
Any help is welcome. Thanks.
EDIT : 10 days after I asked this question, I still don't know how to solve my problem. If anyone could help, even a little, just a clue...
I cannot test this at the moment, but you can try to do something like this:
$collection = Mage::getSingleton('catalog/product_link')
->useRelatedLinks()
->getProductCollection()
->setIsStrongMode();
$product = Mage::getModel('catalog/product')->load($productId);
$collection->setProduct($product);
$collection->addCategoryFilter($category); //I'm not sure if this will work correctly
I'm gonna test it, when I will get some more time.
Actually I just solved my problem by myself.
Here is my solution if it could help anyone in the future :
$mainProduct = Mage::getModel('catalog/category')->load($myCurrentCat->getId());
$mainProduct = $mainProduct->getProductCollection();
$mainProduct = $mainProduct->addAttributeToFilter('product_id', $myVirtualProductId);
foreach ($mainProduct as $product) {
$related = $product->getRelatedProductIds();
if ($this->array_contains($related, $myVirtualProductId)) {
//TODO
}
}

Fetching related objects

In Symfony 2 book there is an example of how to do that for ONE $product: http://symfony.com/doc/2.0/book/doctrine.html#fetching-related-objects
It is quite simple:
public function showAction($id)
{
$product = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Product')
->find($id);
$categoryName = $product->getCategory()->getName();
// ...
}
But what if i want to fetch ALL products with category info joined automatically to each project?
Thank you!
This will do the trick:
$products = $this->getDoctrine()->getRepository('AcmeStoreBundle:Product')->findAll();
However, each time you do a getCategory on a product a sql query will be triggered which could result in performance issues.
What you really want to do is to make yourself a ProductManager service and write an explicit query joining product and category. So only one sql query will be generated. The Doctrine 2 manual has plenty of examples.
http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/reference/query-builder.html
You can either iterate over the products and get the categories from there. Adjusting the fetch mode on the relations might help in reducing the amount of queries performed.
However, you might also just write a custom DQL query to get what you need. It might look like something like this:
SELECT p, c
FROM AcmeStoreBundle:Product p
INNER JOIN p.category c

Resources